测试了一下,是能改到属性值的,表示凌乱了。一般javabean和获取javabean的反射方法是分开的。这是我自己写的一个反射方法,楼主可以看看。- public class User {
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- public class IntroSpectorTest {
- public static void main(String[] args) {
- try {
- User user = new User();
- // 通过内省写入name的值
- String propertyName = "name";
- Object value = "zhangsan";
- setProperty(user, propertyName, value);
- // 通过内省写入age的值
- propertyName = "age";
- value = 21;
- setProperty(user, propertyName, value);
- //打印出结果
- System.out.println(user.getName());
- System.out.println(user.getAge());
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private static void setProperty(Object user, String propertyName, Object value)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pd;
- pd = new PropertyDescriptor(propertyName, user.getClass());
- Method methodSetName=pd.getWriteMethod();
- methodSetName.invoke(user, value);
- }
- }
复制代码 |