前言:本博客内容由张孝祥Java高新技术整理而来
首先是一个javaBean
Stundent
package com.dao.chu.movie;
public class Student {
private int id;
private String name;
private int age;
public Student() {
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
然后是内省操作的测试类,这里面有两个自定义的方法,用来设置属性和获得属性。
IntroSpectorTest
package com.dao.chu.movie;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class IntroSpectorTest {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
Student student = new Student();
setProerties(student,"name","张三");
Object name = getproperties(student, "name");
System.out.println(name);
}
/**
* <p>Title: setProerties</p>
* <p>Description: 设置javabean属性通用方法</p>
* @param t
* @param beanName
* @param setValue
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
private static <T> void setProerties(T t, String beanName,
String setValue) throws IntrospectionException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
Method setnameMethod = new PropertyDescriptor(beanName, t.getClass()).getWriteMethod();
setnameMethod.invoke(t,setValue);
}
/**
* <p>Description:获取javabean属性通用方法</p>
* @param t
* @param beanName
* @return
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
* @throws IntrospectionException
*/
private static <T> Object getproperties(T t,String beanName)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException, IntrospectionException {
Object nameValue = new PropertyDescriptor(beanName, t.getClass()).getReadMethod().invoke(t);
return nameValue;
}
}
输出结果:
张三