jdk1.5——自省(Introspector)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/83030971

通过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;
	}
}

结果:

猜你喜欢

转载自blog.csdn.net/FlyLikeButterfly/article/details/83030971