PropertyDescriptor
程序员文章站
2022-05-24 09:08:47
...
属性描述器PropertyDescriptor
简介:就是通过,传入属性名和类名,获取某个类的实例(也可以先改变类的属性值,再获取类的实例)
例:
//set get toString 方法省略
public class Cat {
private String name;
private String describe;
private int age;
private int weight;
}
//三种构造函数
//1.传入属性名和类名 (实际是调用第二种构造函数,内部拼接了get和set方法调用了第二种构造函数)
PropertyDescriptor CatPropertyOfName = new PropertyDescriptor("name", Cat.class);
//2.第二种构造函数,传入属性名 类名 对应属性的get和set方法名
PropertyDescriptor CatPropertyOfName = new PropertyDescriptor("name", Cat.class,"getName","setName");
//3.第三种构造函数,属性名 属性对应的get和set方法名
Class<?> classType = Cat.class;
Method CatNameOfRead = classType.getMethod("getName");
Method CatNameOfWrite = classType.getMethod("setName", String.class);
PropertyDescriptor CatPropertyOfName = new PropertyDescriptor("name", CatNameOfRead,CatNameOfWrite);
System.out.println(CatPropertyOfName.getPropertyType());
System.out.println(CatPropertyOfName.getPropertyEditorClass());
System.out.println(CatPropertyOfName.getReadMethod());
System.out.println(CatPropertyOfName.getWriteMethod());
结果:
class java.lang.String
null
public java.lang.String entity.Cat.getName()
public void entity.Cat.setName(java.lang.String)
应用:
public static void main(String[] args) throws Exception {
//获取类
Class classType = Class.forName("com.example.demo.beans.Cat");
Object catObj = classType.newInstance();
//获取Name属性
PropertyDescriptor catPropertyOfName = new PropertyDescriptor("name",classType);
//得到对应的写方法
Method writeOfName = catPropertyOfName.getWriteMethod();
//将值赋进这个类中
writeOfName.invoke(catObj,"river");
Cat cat = (Cat)catObj;
System.out.println(cat.toString());
}
输出:
Cat{name=’river’, describe=’null’, age=0, weight=0}
public static void main(String[] args) throws Exception {
//一开始的默认对象
Cat cat = new Cat("river","黑猫",2,4);
//获取name属性
PropertyDescriptor catPropertyOfName = new PropertyDescriptor("name",Cat.class);
//得到读方法
Method readMethod = catPropertyOfName.getReadMethod();
//获取属性值
String name = (String) readMethod.invoke(cat);
System.out.println("默认:" + name);
//得到写方法
Method writeMethod = catPropertyOfName.getWriteMethod();
//修改值
writeMethod.invoke(cat,"copy");
System.out.println("修改后:" + cat);
}
输出:
默认:river 修改后:Cat{name=’copy’, describe=’黑猫’, age=2, weight=4}
3.取http的请求头中的token和appid:
public class ReflectUtils {
//instance传入请求的实例,fieldname传入字符串 “requestHeader”
public static Object invokeGetter(Object instance, String fieldName) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
PropertyDescriptor pd = new PropertyDescriptor(fieldName, instance.getClass());
return pd.getReadMethod().invoke(instance);
}
}
RequestHeaderType questHeader=(RequestHeaderType) ReflectUtils.invokeGetter(request,“requestHeader”);
questHeader.getToken();
questHeader.getAppId();
参考:https://unclecatmyself.github.io/2019/01/19/propertyDescriptor/