java内省

来源:互联网 发布:质谱软件 编辑:程序博客网 时间:2024/05/22 01:32

JDK提供了对JavaBean来进行操作的一些api,这套api就称为内省。

通过内省方式得到ReflectPoint类中的x的属性值,并且把该属性值设置为10

ReflectPoint类:

public class ReflectPoint {

private int x=3;

public int getX() {
  return x;
 }


 public void setX(int x) {
  this.x = x;
 }

}

 

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntrospectorTest {

 public static void main(String[] args) throws Exception {
  
    ReflectPoint p=new ReflectPoint();
  
    String methodName="x";
    PropertyDescriptor  pd=new PropertyDescriptor(methodName,p.getClass());
    Method method=pd.getReadMethod();//得到读取方法
    Object obj=method.invoke(p, null);//反射调用该方法
    System.out.println(obj);
  
     Method method2= pd.getWriteMethod();//得到写方法
     method2.invoke(p, 10);//反射调用该方法,并把该对象的x的值设置为10
     obj=method.invoke(p, null);
     System.out.println(obj);
  
  
 }

}

 

以上也可以换一种方式得到x的值

采用遍历BeanInfo的所有属性的方式来查找和设置某个对象的x值

BeanInfo beanInfo=Introspector.getBeanInfo(p.getClass());
PropertyDescriptor[]pds=beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pdo:pds){
   if(pdo.getName().equals(methodName)){
    
    Method method3=pdo.getReadMethod();
    Object obj1=method3.invoke(p, null);
    System.out.println(obj1);
   }

 

 

使用Beanutils工具包操作javabean

  System.out.println(BeanUtils.getProperty(p, methodName));//取得值
  BeanUtils.setProperty(p, methodName, 12);
  System.out.println(BeanUtils.getProperty(p, methodName));

 

0 0
原创粉丝点击