jdk1.5——自省(Introspector)

通過Introspector獲得JavaBean的屬性、方法;注意JavaBean裏的命名規範;

Demo:

/**
 * 2018年10月12日下午3:47:58
 */
package testIntrospector;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author XWF
 *
 */
public class TestIntrospector {

	/**
	 * @param args
	 * @throws IntrospectionException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	public static void main(String[] args) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		MyJavaBean obj = new MyJavaBean(123,"helloworld");
		//通過PropertyDescriptor直接獲得
		PropertyDescriptor pd = new PropertyDescriptor("x", MyJavaBean.class);
		Method getxm = pd.getReadMethod();
		int xValue = (int) getxm.invoke(obj, null);
		System.out.println("x="+xValue);
		
		pd = new PropertyDescriptor("y", MyJavaBean.class, "getYY", "setY");//設置自定義的getYY
		Method setym = pd.getWriteMethod();
		Method getym = pd.getReadMethod();
		System.out.println("1.y="+getym.invoke(obj, null));
		setym.invoke(obj, "HELLO JAVA");
		System.out.println("2.y="+getym.invoke(obj, null));
		
		//通過Introspector的BeanInfo獲得,是通過方法名獲得的,會把getYY映射成一個叫YY的屬性,而缺失getY方法
		BeanInfo binfo = Introspector.getBeanInfo(MyJavaBean.class);
		PropertyDescriptor[] pds = binfo.getPropertyDescriptors();
		for(PropertyDescriptor propertyDescriptor:pds) {
			System.out.println("---------------");
			System.out.println("type:"+propertyDescriptor.getPropertyType()+" name:"+propertyDescriptor.getName());
			System.out.println("getMethod:"+propertyDescriptor.getReadMethod());
			System.out.println("setMethod:"+propertyDescriptor.getWriteMethod());
		}
	}

}
class MyJavaBean{
	private int x;
	private String y;
	
	public MyJavaBean(int x, String y) {
		super();
		this.x = x;
		this.y = y;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public String getYY() {//自定義get方法
		return y;
	}
	public void setY(String y) {
		this.y = y;
	}
}

結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章