反射

实体类

public class TestBean {
    String name;
    int age;
    private TestBean() {

    }

    public TestBean(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName(){
        return name;
    };

    public void setName(String name){
          this.name = name;
    }; 
    private int  getAge(){
        return age;
    }
}

反射获取实例

//无参构造(私有)
TestBean testBean = TestBean.class.newInstance();
//无参构造(公有)
Constructor<TestBean> constructor = TestBean.class.getConstructor();
TestBean testBean = constructor.newInstance();
//无参构造(私有)
Constructor<TestBean> constructor = TestBean.class.getDeclaredConstructor();
constructor.setAccessible(true);
TestBean testBean = constructor.newInstance();
//有参构造(私有)
Constructor<TestBean> constructor = TestBean.class.getDeclaredConstructor(String.class, int.class);
constructor.setAccessible(true);
TestBean testBean = constructor.newInstance("woochen123", 23);

反射获取方法

//获取方法(公有)
//参数1:方法名      参数2:方法参数类型的class对象(集合)
Method method = TestBean.class.getMethod("setName",String.class);
//参数1:执行方法的对象(静态方法可以传null)      参数2:方法需要的参数
method.invoke(testBean,"woochen123");

//获取方法(私有)
Method method = TestBean.class.getDeclaredMethod("getAge");
method.setAccessible(true);
method.invoke(testBean,null);

//补充
declaredMethod.getReturnType()   //获得返回值
declaredMethod.getGenericReturnType() //获得完整信息的返回值
 Class<?>[] parameterTypes = declaredMethod.getParameterTypes(); //获得参数类型
Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes();     //获得异常名称
 Annotation[] annotations = declaredMethod.getAnnotations(); //获得注解

反射获取属性

//属性(公有)
 Field field = TestBean.class.getField("name");
//获取属性   参数:属性所在的对象(如果是静态属性可以传null)
 String name = (String) field.get(testBean);
//设置属性 参数1:属性所在的对象(如果是静态属性可以传null)  参数2:给属性赋的值
field.set(testBean,"woochen123");

//属性(私有)
Field field = TestBean.class.getDeclaredField("name");
field.setAccessible(true);
String name = (String) field.get(testBean);
field.set(testBean,"woochen123");

//补充
field.getType():返回这个变量的类型
field.getGenericType():如果当前属性有签名属性类型就返回,否则就返回 Field.getType()

补充

  • testBean.getClasses()
    返回调用类的所有公共类、接口、枚举组成的 Class 数组,包括继承的
  • testBean.getModifiers()
    获得调用类的修饰符的二进制值
  • Modifier.toString(int modifiers)
    将二进制值转换为字符串

注意

  • 只有被 @Retention(RetentionPolicy.RUNTIME) 修饰的注解才可以在运行时被反射获取
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Java反射 概述 Java反射机制可以让我们在编译期(Compile Time)之外的运行期(Runtime)检...
    Leocat阅读 4,804评论 0 0
  • 前言,本来只是想研究一下注解的,不过发现,要懂注解先得懂反射,别问我为什么,你可以自己试试 JAVA反射 主要是指...
    justCode_阅读 4,943评论 2 9
  • 整体Retrofit内容如下: 1、Retrofit解析1之前哨站——理解RESTful 2、Retrofit解析...
    隔壁老李头阅读 10,123评论 2 12
  • 1.反射含义是什么? Java反射机制是指在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意...
    Marlon666阅读 3,003评论 0 0
  • 总结内容源自一下文章粗浅看java反射机制反射机制应用实践谈谈java反射机制Java Reflection(反射...
    天外之石阅读 2,435评论 0 0

友情链接更多精彩内容