------- 物联云培训、java培训、期待与您交流! ----------
内省
实际上是一种专门反射JavaBean类的。
JavaBean类是一个特殊的类,其属性都有其对应的get和set方法的那么一个类就成为JavaBean类。
示例代码:
public class Person {
public String name;
public int age;
public int[] number={1,2,3,4};
public Person() {
name="daiwenjuan";
age=22;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = 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;
}
}
而内省就是专门用于反射JavaBean类
示例代码:
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.BeanUtils;
importorg.apache.commons.beanutils.PropertyUtils;
public class javabeanDemo {
public static void main(String[] args)throws Exception{
Person person=new Person("daiwenjuanailichao",100);
String classname="name";
/*//内省
PropertyDescriptorpp=new PropertyDescriptor(classname,person.getClass());
Method method1=pp.getWriteMethod();
method1.invoke(person, "lichaoaidaiwenjuan");
Method method=pp.getReadMethod();
System.out.println(method.invoke(person, null));*/
/*BeanInfoinfo=Introspector.getBeanInfo(person.getClass());
PropertyDescriptor[] pp=info.getPropertyDescriptors();
for(PropertyDescriptor pop:pp){
if(pop.getName().equals(classname)){
Method method=pop.getReadMethod();
System.out.println(method.invoke(person,null));
}
}*/
//用工具包实现内省
BeanUtils.setProperty(person,classname, "lichaoaidaiwenjuan");//设置属性值
System.out.println(BeanUtils.getProperty(person,classname)); //获得属性值
PropertyUtils.setProperty(person,classname, "ainijuanjuan");//属性值属性必须一致
}
}
总结:内省就是特殊的反射。