Java反射机制对于Javabean的内省(Javabean的一些反射的demo)
package com.omg.demo;
public class Person {
private int age;
private String name;
public Person(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.omg.demo;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author Administrator
* java的内省的实例,通过对bean的反射进行设置和获取Person实例的get和set的值
*/
public class IntrospectorTest {
public static void main(String[] args) throws Exception{
Person person = new Person(25, "张三");
String propertyName = "name";
PropertyDescriptor prop = getProperties(person, propertyName);
/**获取写的方法***/
String name = "李四";
setProperties(person, prop, name);
}
/**
* 用内省的方式进行得到set的属性的内容
* @param person
* @param prop
* @param name
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static void setProperties(Person person, PropertyDescriptor prop,
String name) throws IllegalAccessException,
InvocationTargetException {
Method writeMethod = prop.getWriteMethod();
writeMethod.invoke(person,name);
System.out.println(person.getName());
}
/**
* 用内省的方式获取属性的值
* @param person
* @param propertyName
* @return
* @throws IntrospectionException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
private static PropertyDescriptor getProperties(Person person,
String propertyName) throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
PropertyDescriptor prop = new PropertyDescriptor(propertyName, person.getClass());
/****获取反射的读取的方法****/
Method method = prop.getReadMethod();
/**执行方法***/
Object object = method.invoke(person);
System.out.println(object);
return prop;
}
}
采用Introspector.getBeanInfo()的方法来进行相关的内省的操作,具体的实例如下展示:
try {
BeanInfo beanInfo = Introspector.getBeanInfo(person.getClass());
PropertyDescriptor [] props = beanInfo.getPropertyDescriptors();
if(props!=null&&props.length>0){
for(PropertyDescriptor newProp :props){
if(newProp.getName().equals("name")){
Method method = newProp.getReadMethod();
Object object = method.invoke(person);
System.out.println(object);
}
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
}