
正文
JAVA反射之 Field (属性)
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
主要方法:
public static void main(String[] args) throws Exception {
Class<?> clazz = Class.forName("Person");
//得到类中所有方法,返回一个数组
Field[] fileds = clazz.getFields();
//得到所有方法包括私有方法
Field[] fields2 = clazz.getDeclaredFields();
//得到方法
Field field = clazz.getDeclaredField("name");
//暴力访问,访问私有属性
field.setAccessible(true);
//通过类实例化对象,通过调用类的无参构造器去实例化对象
Object object = clazz.newInstance();
//给对象属性赋值
field.set(object, "hhh");
//对象类型
Class s = field.getType();//class java.lang.String
System.out.println(s);
//对象名称
field.getName();
//获取对象属性值
field.get("name");
}
暴力访问会破坏对象的封装性,解决方法为:
//破坏封装性,解决方式(内省机制):
Class<?> clazz1 = Class.forName("Person");
// 创建对象
Object person = clazz1.newInstance();
// 获得属性描述器
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("setName", clazz1);
// 获得set方法
Method setMethod = propertyDescriptor.getWriteMethod();
// 调用方法 person.setName("jack");
setMethod.invoke(person, "jack");
System.out.println(person);







