阅读:2122次   评论:0条   更新时间:2013-08-14    
反射技术实际是已经能够完全满足我们对javaBean的各种操作了,但是为了方便JDK还是为我们提供了一套操纵JavaBean的API,我们称这套API为内省操作(Introspector),下面示范一下通常的两种内省操作.

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

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中的方法时很管用

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


第二种方法是对于某个特定的属性

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的内省操作
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics