JDK中提供了对JavaBean进行操作的一些API,这套API就成为内省。
对JavaBean的简单内省操作:
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class IntroSpectorTest {
public static void main(String[] args) throws Exception{
Person person = new Person("alex",24);
String propertyName = "name";
Object beanObj = person;
Object setValue="zhuang";
setPropertyValue(propertyName, beanObj, setValue);
Object returnValue = getPropertyValue(propertyName, beanObj);
System.out.println(returnValue);
}
public static void setPropertyValue(String propertyName, Object beanObj,
Object setValue) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,beanObj.getClass());
Method setPropertyValue = pd.getWriteMethod();
setPropertyValue.invoke(beanObj, setValue);
}
public static Object getPropertyValue(String propertyName, Object beanObj)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,beanObj.getClass());
Method getPropertyValue = pd.getReadMethod();
Object returnValue = getPropertyValue.invoke(beanObj, null);
return returnValue;
}
输出结果为: zhuang