javaBean的内省操做

反射技术实际是已经可以彻底知足咱们对javaBean的各类操做了,可是为了方便JDK仍是为咱们提供了一套操纵JavaBean的API,咱们称这套API为内省操做(Introspector),下面示范一下一般的两种内省操做. java

既然内省是做用于javaBean的,那么咱们先提供一个JavaBean类,本例为UserBean.java this

 

package net.csdn.blog;

public class UserBean {

	private String name;
	private int age;

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

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

}

方法一:第一种方法为较繁琐的一种方法,但一般在批量操纵javaBean中的方法时很管用。 spa

package net.csdn.blog;

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;

public class UserBeanHandlerOne {

	public static void main(String args[]) {
		UserBean user = new UserBean();
		try {
			handleBean(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void handleBean(UserBean user)
			throws IntrospectionException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		BeanInfo bi = Introspector.getBeanInfo(user.getClass());
		PropertyDescriptor[] pd = bi.getPropertyDescriptors();
		for (PropertyDescriptor p : pd) {
			String attrName=p.getName();
			if(attrName.equals("name")||attrName.equals("age")){
				Method writeMethod=p.getWriteMethod();//获得set方法
				Class clazz[]=writeMethod.getParameterTypes();
				if(clazz[0]==int.class)
				      writeMethod.invoke(user, 20);
				else
					writeMethod.invoke(user, "peter");//执行set方法
				Method readMethod = p.getReadMethod();//获取get方法
				Object obj = readMethod.invoke(user);//执行get方法
				System.out.println(obj);
			}
		}
	}
}



方法二: 第二种方法是对于某个特定的属性
package net.csdn.blog;

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

public class UserBeanHandlerTwo {

	
	public static void main(String args[]) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		UserBean ub=new UserBean();
		PropertyDescriptor pd=new PropertyDescriptor("name",UserBean.class);
		Method writeMethod=pd.getWriteMethod();
		writeMethod.invoke(ub,"peter");
		Method readMethod=pd.getReadMethod();
		Object str=readMethod.invoke(ub);
		System.out.println(str);
	}
}



这两种方法都可以用来做为javaBean的内省操做 。
相关文章
相关标签/搜索