本质就是反射.
是由sun公司提供,集成到jdk。
核心类:
PropertyDescriptor - 属性描述器
API:
PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
以下javaBean拥有get and set就是一对,就可以通过PropertyDescorptor来操作。
JavaBean的定义
拥有无参数构造。
拥有一个get | set | isXxxx方法。
如果希望被内省使用
必须
拥有元参数构造
拥有一对get && setXxx | isXxxx方法
以示示例演示如何用操作:
PropertyDescriptor.getReadMethod() - 获取某个Bean中的getXxxx
是由sun公司提供,集成到jdk。
核心类:
PropertyDescriptor - 属性描述器
API:
PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
以下javaBean拥有get and set就是一对,就可以通过PropertyDescorptor来操作。
JavaBean的定义
拥有无参数构造。
拥有一个get | set | isXxxx方法。
如果希望被内省使用
必须
拥有元参数构造
拥有一对get && setXxx | isXxxx方法
以示示例演示如何用操作:
PropertyDescriptor.getReadMethod() - 获取某个Bean中的getXxxx
PropertyDescriptor.getWriteMethod() – 某个bean setXxxx方法。
public void demo1() throws Exception{
//第一个类
User o = new User();
// Method setName = o.getClass().getMethod("setName",String.class);
// setName.invoke(o, "Jack");
// System.err.println(o);
//
//以下通过内省实现
PropertyDescriptor pd =
new PropertyDescriptor("name",o.getClass(),"getMyName","setName");
//获取设置属性方法
/**
* getReadMethod = getXxxx
* getWriteMethod = setXxxx
*/
Method setMethod= pd.getWriteMethod();
setMethod.invoke(o,"Rose");
System.err.println(">>:"+o);
}
内省与参数类型
@Test
public void demo1() throws Exception{
//第一个类
User o = new User();
PropertyDescriptor pd =
new PropertyDescriptor("age", o.getClass());
Method m = pd.getWriteMethod();
m.invoke(o,90);//接收的Integer
System.err.println(">>:"+o);
}
内省与BeanInfo
BeanInfo专门用于分析一个Bean拥有多少属性:
/**
* 通过Beaninfo获取一个类的所有setXxx|getXxx|isXxx方法
*/
@Test
public void beaninfo() throws Exception{
BeanInfo info =
Introspector.getBeanInfo(User.class);
PropertyDescriptor[] pd = info.getPropertyDescriptors();
for(PropertyDescriptor p:pd){
String name = p.getName();
System.err.println(name);
// Method m = p.getWriteMethod();//setXxx(....);
// Class<?>[] cls = m.getParameterTypes();
// System.err.println(cls.length);
}
}
遍历方法
public class MethodReflect {
public static void main(String[] args) throws Exception {
String name = "name";
String value = "90";
A a = new A();
Method[] ms = a.getClass().getDeclaredMethods();
for(Method m:ms){
String nm = m.getName();//setName
System.err.println(nm);
if(nm.startsWith("set")){
Class<?>[] clss = m.getParameterTypes();
System.err.println(clss[0]);
if(clss[0].equals(String.class)){
m.invoke(a,value);
}else if(clss[0].equals(Integer.class)){
m.invoke(a,Integer.valueOf(value));
}
}
}
System.err.println(a);
}
}