利用内省方式对JavaBean的属性设置和取值

package com.zchen.bean;

public class Point {

	private int x;

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}
	
}
  package com.zchen.bean;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class IntroSpactorTest {

	public static void main(String[] args) throws Exception{
		Point point = new Point();
		String propertyName = "x";
		Object value = 9;
		setProperties(point, propertyName, value);
		Object val = getProperties(point, propertyName);
		System.out.println(val);
	}

	private static void setProperties(Object point, String propertyName,
			Object value) throws Exception{
		PropertyDescriptor pd1 = new PropertyDescriptor(propertyName, point.getClass());
		Method methodSetX = pd1.getWriteMethod();
		methodSetX.invoke(point, value);
	}
	private static Object getProperties(Object point, String propertyName) throws Exception{
		PropertyDescriptor pd2 = new PropertyDescriptor(propertyName, point.getClass());
		Method methodGetX = pd2.getReadMethod();
		Object retVal = methodGetX.invoke(point);
		return retVal;
	}

}
 

你可能感兴趣的:(bean)