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

结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值