反射

2017-09-04  本文已影响0人  woochen123

实体类

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()

补充

注意

上一篇 下一篇

猜你喜欢

热点阅读