A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑马张国礼 初级黑马   /  2012-6-11 21:37  /  1867 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

ReflectPoint pt1=new ReflectPoint(3,5);
String propertyName="x";
PropertyDescriptor pd=new PropertyDescriptor(propertyName,pt1.getClass());
Method methodGetX=pd.getReadMethod();
Object retval=methodGetX.invoke(pt1);
System.out.println(retval);
既然已经知道类中存在了getX()方法,那么直接使用
System.out.println(pt1.getX());多直接啊,为什么还要用这么些复杂的方法呢???

1 个回复

倒序浏览
  1. public class Main{
  2.     public static void main(String[] args) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {
  3.             ReflectPoint pt1=new ReflectPoint(3);
  4.             String propertyName="x";
  5.             PropertyDescriptor pd=new PropertyDescriptor(propertyName,pt1.getClass());
  6.             Method methodGetX=pd.getReadMethod();//这里返回的是默认的getX方法。
  7.             Object retval=methodGetX.invoke(pt1);//执行默认getX方法。
  8.             System.out.println(retval);//输出3
  9.             Method m = pt1.getClass().getMethod("myGetFuncation",null);//获取类中myGetFuncation方法的Method对象
  10.             pd.setReadMethod(m);//将自定义的方法设置为x的默认读取方法
  11.             Method anotherMethodGetX=pd.getReadMethod();//再次取得x的默认获取方法,只是此时的默认获取方法已被我们改变了。
  12.             Object retval2=anotherMethodGetX.invoke(pt1);
  13.             System.out.println(retval2);//输出103
  14.     }
  15. }
  16. class ReflectPoint {
  17.         int x;
  18.         public ReflectPoint(int x){
  19.                 this.x = x;
  20.         }
  21.         public int getX() {//默认x的获取方法
  22.                 return x;
  23.         }
  24.         public void setX(int x) {
  25.                 this.x = x;
  26.         }
  27.         public int  myGetFuncation() {//自定义一个也可获取x值的方法,但是会把x加上100后返回。
  28.                 return x+100;
  29.         }
  30. }
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马