标签:
用内省来操作Bean会给程序带来很大的便利,特别是在很大的实体对象的时候,在其属性很多的时候要为其赋值的时候,
package com.bean; public class User { private String uid; private String userName; private String userPass; private String age; private String sex; public User(){} public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPass() { return userPass; } public void setUserPass(String userPass) { this.userPass = userPass; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public User(String uid, String userName, String userPass, String age, String sex) { super(); this.uid = uid; this.userName = userName; this.userPass = userPass; this.age = age; this.sex = sex; } @Override public String toString() { return "User [uid=" + uid + ", userName=" + userName + ", userPass=" + userPass + ", age=" + age + ", sex=" + sex + "]"; } }
package com.bean; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; public class beanUtils { /** * java内省 * @param args * @throws IntrospectionException * @throws InvocationTargetException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { BeanInfo beanInfo = Introspector.getBeanInfo(User.class, Object.class); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); User user = new User(); for(PropertyDescriptor pd : pds){ System.out.println(pd.getName()); } PropertyDescriptor pd = new PropertyDescriptor("age", User.class); pd.getWriteMethod().invoke(user, "22"); System.out.println(pd.getReadMethod().invoke(user)); } }
age sex uid userName userPass 22
标签:
原文地址:http://www.cnblogs.com/dbqjava/p/5327966.html