`
hejianmingwshjmcj
  • 浏览: 11920 次
  • 性别: Icon_minigender_1
  • 来自: 江西
最近访客 更多访客>>
社区版块
存档分类
最新评论

JavaBean属性方法反射

阅读更多
public class ReflectPoint {

public int x;
public int y;
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

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

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}



import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IntroSpectorTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception{
ReflectPoint rp = new ReflectPoint(1,2);
getPorperties(rp);

getProperties(rp);

Object y = 7;
SetProterties(rp, y);
}

//用反射获得指定JAVABean属性的值
private static void getPorperties(ReflectPoint rp)
throws Exception {
Field field = rp.getClass().getDeclaredField("x");
System.out.println(field.get(rp));;
}

//用反射设置指定JAVABean属性的值
private static void SetProterties(Object rp, Object y)
throws Exception{
PropertyDescriptor pd2 = new PropertyDescripto("y",rp.getClass());
Method method = pd2.getWriteMethod();

method.invoke(rp, y);
System.out.println(((ReflectPoint) rp).getY());
}

//用反射获得指定JAVABean属性的值
private static void getProperties2(Object rp)
throws Exception{
PropertyDescriptor pd = new PropertyDescriptor("x",rp.getClass());
Method methodGetx = pd.getReadMethod();
Object retvalx = methodGetx.invoke(rp);
System.out.println(retvalx.getClass().getName());
}

}
1
0
分享到:
评论
1 楼 youthon 2012-04-24  
楼主的代码有几处小错误啊

相关推荐

Global site tag (gtag.js) - Google Analytics