- package com.sf.test;
- public class TestJavaBeans {
- /**
- * @param args
- */
- private int x;
- private int 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;
- }
- }
复制代码- package com.sf.test;
- import java.beans.IntrospectionException;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Method;
- public class WeekDay {
- /**
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- String propertyName="x";
- TestJavaBeans test=new TestJavaBeans();
- test.setX(4);
- test.setY(5);
- PropertyDescriptor properties=new PropertyDescriptor(propertyName, test.getClass());
- Method getMethod=properties.getReadMethod();
- System.out.println(getMethod.invoke(test));
- Method setMethod=properties.getWriteMethod();
- setMethod.invoke(test, 10);
- System.out.println(getMethod.invoke(test));
- System.out.println(test.getX());
- }
- }
复制代码
如上,明明可以直接用test的set和get方法来读和设置值,为什么要弄一大堆先通过PropertyDescriptor获取属性,然后通过属性获得方法,然后再通过反射执行读取和设值方法,我怎么不明白他这么做到底有什么必要呢?求哪位大神帮忙具体说清楚点这么用的好处. |
|