java反射机制(3)---关于Javabean的内省

Java反射机制对于Javabean的内省(Javabean的一些反射的demo)

package com.omg.demo;

public class Person {
	private int age;
	private String name;
    
	public Person(int age, String name) {
		super();
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


package com.omg.demo;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Administrator
 * java的内省的实例,通过对bean的反射进行设置和获取Person实例的get和set的值
 */
public class IntrospectorTest {
    public static void main(String[] args) throws Exception{
		Person person = new Person(25, "张三");
		String propertyName = "name";
		PropertyDescriptor prop = getProperties(person, propertyName);
		/**获取写的方法***/
		String name  = "李四";
		setProperties(person, prop, name);
	}
    /**
     * 用内省的方式进行得到set的属性的内容
     * @param person
     * @param prop
     * @param name
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
	private static void setProperties(Person person, PropertyDescriptor prop,
			String name) throws IllegalAccessException,
			InvocationTargetException {
		Method writeMethod = prop.getWriteMethod();
		writeMethod.invoke(person,name);
		System.out.println(person.getName());
	}
     
	/**
	 * 用内省的方式获取属性的值
	 * @param person
	 * @param propertyName
	 * @return
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 */
	private static PropertyDescriptor getProperties(Person person,
			String propertyName) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		PropertyDescriptor prop = new PropertyDescriptor(propertyName, person.getClass());
		/****获取反射的读取的方法****/
		Method method = prop.getReadMethod();
		/**执行方法***/
		Object object = method.invoke(person);
		System.out.println(object);
		return prop;
	}
}

采用Introspector.getBeanInfo()的方法来进行相关的内省的操作,具体的实例如下展示:

try {
			BeanInfo beanInfo = Introspector.getBeanInfo(person.getClass());
			PropertyDescriptor [] props = beanInfo.getPropertyDescriptors();
			if(props!=null&&props.length>0){
				for(PropertyDescriptor newProp :props){
					if(newProp.getName().equals("name")){
						Method method = newProp.getReadMethod();
						Object object = method.invoke(person);
						System.out.println(object);
					}
				}
			}
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值