有时候我们只知道一个对象的字段,我们想通过反射的方式将此字段赋值,可直接写反射又太浪费时间,还需要自己手动拼接方法名,而java为我们提供了一个很方便的类(PropertyDescriptor)来操作这一过程。使用很简单,直接看代码:
代码
import com.pibgstar.demo.bean.User;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author pibigstar
* @create 2018-12-03 18:36
* @desc
**/
public class TestPropertyDescriptor {
public static void main(String[] args){
TestPropertyDescriptor test = new TestPropertyDescriptor();
User user = new User();
user.setId("123");
Object id = test.getAttribute("id", user);
System.out.println("id:"+id.toString());
test.setAttribute("name",user,"pibigstar");
System.out.println(user);
}
/**
* @Author:pibigstar
* @Description: 根据字段获取属性值
*/
private Object getAttribute(String filed,Object obj) {
try {
PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
// 获取getter方法
Method method = pd.getReadMethod();
Object result = method.invoke(obj);
return result;
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
/**
* @Author:pibigstar
* @Description: 设置属性字段值
*/
private void setAttribute(String filed,Object obj,Object value) {
try {
PropertyDescriptor pd = new PropertyDescriptor(filed,obj.getClass());
// 获取setter方法
Method method = pd.getWriteMethod();
method.invoke(obj, value);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
User对象也放一下吧
public class User {
private String id;
private String name;
// setter/getter 方法
}
运行结果
id:123
User{id='123', name='pibigstar'}