内省
Introspector
1. getPropertyType(),获得属性的Class对象;
2. getReadMethod(),获得用于读取属性值的方法;getWriteMethod(),获得用于写入属性值的方法;
3. hashCode(),获取对象的哈希值;
4. setReadMethod(Method readMethod),设置用于读取属性值的方法;
5. setWriteMethod(Method writeMethod),设置用于写入属性值的方法。
public
static
void
setProperty(UserInfo userInfo,String userName)
throws
Exception{
PropertyDescriptor propDesc=
new
PropertyDescriptor(userName,UserInfo.
class
);
Method methodSetUserName=propDesc.getWriteMethod();
methodSetUserName.invoke(userInfo,
"wong"
);
System.out.println(
"set userName:"
+userInfo.getUserName());
PropertyDescriptor proDescriptor =
new
PropertyDescriptor(userName,UserInfo.
class
);
Method methodGetUserName=proDescriptor.getReadMethod();
Object objUserName=methodGetUserName.invoke(userInfo);
System.out.println(
"get userName:"
+objUserName.toString());
}
反射机制
AstAsset where = new AstAsset(); where.setAssetNo("WKZC-202104-0003"); where.setCreateTime(new Date()); // createTime 是继承父类 where.setOnlineFlag(OnlineFlag.ONLINE); Field createTime = ReflectionUtils.findField(AstAsset.class, "createTime"); createTime.setAccessible(true); 因为是private属性所以设置可见,否则不可访问IllegalAccessException Object o = createTime.get(where); Class<?> type = createTime.getType(); System.out.println(o); System.out.println(type);
工具
BeanUtils org.apache.commons.beanutils
String createTime = org.apache.commons.beanutils.BeanUtils.getProperty(where, "createTime"); System.out.println(createTime); 该方法获取的只能是返回string类型,做了onverted to a String。public static void populate(final Object bean, final Map<String, ? extends Object> properties)public static Map<String, String> describe(final Object bean)
PropertyUtils
public static Object getProperty(final Object bean, final String name) 根据属性获取值对象,包括Date,Enum等类型,不能是嵌套的或者map复杂类型。
SerializedLambda :根据get 的lambda的方法获取属性米名称
开源源码片段: task == AstAsset::getCreateTime
SerializedLambda lambda;
try {
Method writeReplace = task.getClass().getDeclaredMethod("writeReplace"); // task lambda 表达式 实现Serializable
writeReplace.setAccessible(true);
lambda = (SerializedLambda) writeReplace.invoke(task);lambda.getImplMethodName(); 获取到getCreateTime 发方法名称
String createTime = PropertyNamer.methodToProperty(lambda.getImplMethodName());
PropertyNamer 是org.apache.ibatis.reflection.property ,methodToProperty 方法去掉get,set ,首字母变小写
} catch (Exception ex) {
throw new IllegalArgumentException("Lambda should implement java.io.Serializable interface", ex);
}
className = lambda.getCapturingClass().replace('/', '.'); 哪个类调用