Java内省操作( java.beans API 的类)

一、Java内省介绍(Java内省操作JavaBean)

        1、在做web开发的时候会大量用到JavaBean属性来封装数据,所以用Java内省操作节省了大量编码

        2、JavaBean到底有什么属性,不由属性决定,由get 或 set 方法决定

        3、可以用反射的方式操作JavaBean,但是JDK提供了 java.beans.*的API里提供了简便的对JavaBean的操作

        4、在网上看作者博客文章,据说Struts封装Bean的属性的时候也用了Java的内省操作来实现的。

二、Java内省代码操作Student类

package com.java.a.introspector;

public class Student {

	private String name;
	private int luckyNum;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getLuckyNum() {
		return luckyNum;
	}
	public void setLuckyNum(int luckyNum) {
		this.luckyNum = luckyNum;
	}
}
package com.java.a.introspector;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;

/**
 * Java内省操作JavaBean
 * @author TS
 */
public class IIntrospector {

	/**
	 * 获取传入JavaBean的所有属性,包含其父类属性
	 * @throws Exception
	 */
	@Test
	public void test() throws Exception{
		//传入要内省的Class对象,获取BeanInfo
		BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
		//通过BeanInfo获取属性描述器数组
		PropertyDescriptor[] pds  =  beanInfo.getPropertyDescriptors();
		//获取Student所有的属性(继承父类属性:class,luckyNum,name)
		for (PropertyDescriptor pd : pds) {
			System.out.println(pd.getName());		
			
		}
	}

	/**
	 * 获取传入JavaBean的所有属性,不包含其父类属性
	 * @throws Exception
	 */
	@Test
	public void test1() throws Exception{
                //始停止分析的基类的JavaBean属性
		BeanInfo beanInfo = Introspector.getBeanInfo(Student.class,Object.class);
		PropertyDescriptor[] pds  = beanInfo.getPropertyDescriptors();
		//获取Student所有的属性(luckyNum,name),不获取Object父类的属性
		for (PropertyDescriptor pd : pds) {
			System.out.println(pd.getName());	
		}
	}
	
	/**
	 * 获取传入的JavaBean的指定属性
	 * @throws Exception
	 */
	@Test
	public void test2() throws Exception{
		
		Student s = new Student();
		//获取指定的Bean属性(字段)
		PropertyDescriptor pd = new PropertyDescriptor("luckyNum", Student.class);
		
		//获取属性的真实类型
		System.out.println( pd.getPropertyType() );			
		
		//获取属性的写方法,为属性赋值
		Method method = pd.getWriteMethod();
		//调用set方法
		method.invoke(s, 47);
		System.out.println(s.getLuckyNum());
		
		//调用读方法( getXX() )
		Method method2 = pd.getReadMethod();
		
		System.out.println( method2.invoke(s, null) );
		
		
		
	}

}




转载于:https://my.oschina.net/tianshuo/blog/648809

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值