Java内省机制-Introspectorhtml
内省(Introspector) —— 为了让程序员们更好的从左Java对象的属性,SUN公司开发了一套API,就被咱们称为“内省”,有利于咱们对类对象的属性的操做,减小了代码的数量。也能够应用于建立Java Beans和Javadocs中。JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的字段,且方法名符合某种命名规则。java
在类UserInfo中有属性userName,那咱们能够经过getUserName,setUserName来获得其值或者设置新的值。经过getUserName/setUserName来访问 userName属性,这就是默认的规则。Java JDK中提供了一套 API用来访问某个属性的 getter/setter方法,这就是内省。程序员
PropertyDescriptor类:测试
PropertyDescriptor类表示JavaBean类经过存储器导出一个属性。主要方法:this
getPropertyType(),得到属性的Class对象;spa
getReadMethod(),得到用于读取属性值的方法;getWriteMethod(),得到用于写入属性值的方法;code
hashCode(),获取对象的哈希值;htm
setReadMethod(Method readMethod),设置用于读取属性值的方法;对象
setWriteMethod(Method writeMethod),设置用于写入属性值的方法。blog
Introspector类:
将JavaBean中的属性封装起来进行操做。在程序把一个类当作JavaBean来看,就是调用Introspector.getBeanInfo()方法,获得的BeanInfo对象封装了把这个类当作JavaBean看的结果信息,即属性的信息。
getPropertyDescriptors(),得到属性的描述,能够采用遍历BeanInfo的方法,来查找、设置类的属性。
实例代码,
package introspector; public class UserInfo { private long userId; private String userName; private int age; private String emailAddress; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } }
测试代码:
package introspector; import org.junit.Test; 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; /** * Created with IntelliJ IDEA. * User: ASUS * Date: 14-7-10 * Time: 下午4:41 * To change this template use File | Settings | File Templates. */ public class IntrospectorTest { @Test public void test0877() throws IntrospectionException, InvocationTargetException, IllegalAccessException { String userNameDesc = "userName"; UserInfo userInfo = new UserInfo(); /** * @param propertyName The programmatic name of the property. * @param beanClass The Class object for the target bean. For * example sun.beans.OurButton.class. */ PropertyDescriptor propDesc = new PropertyDescriptor(userNameDesc, UserInfo.class); Method methodSetUserName = propDesc.getWriteMethod(); methodSetUserName.invoke(userInfo, "lyx"); System.out.println("set userName:" + userInfo.getUserName()); } @Test public void test98776776() throws IntrospectionException, InvocationTargetException, IllegalAccessException { String userNameDesc = "userName"; UserInfo userInfo = new UserInfo(); PropertyDescriptor proDescriptor = new PropertyDescriptor(userNameDesc, UserInfo.class); Method methodGetUserName = proDescriptor.getReadMethod(); userInfo.setUserName("sdsdsdsd"); Object objUserName = methodGetUserName.invoke(userInfo); System.out.println("get userName:" + objUserName.toString()); } @Test public void test755() throws IntrospectionException, InvocationTargetException, IllegalAccessException { String userNameDesc = "userName"; UserInfo userInfo = new UserInfo(); BeanInfo beanInfo = Introspector.getBeanInfo(UserInfo.class); PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors(); if (proDescrtptors != null && proDescrtptors.length > 0) { for (PropertyDescriptor propDesc : proDescrtptors) { if (propDesc.getName().equals(userNameDesc)) { Method methodSetUserName = propDesc.getWriteMethod(); methodSetUserName.invoke(userInfo, "alan"); System.out.println("set userName:" + userInfo.getUserName()); break; } } } } @Test public void test98765() throws IntrospectionException, InvocationTargetException, IllegalAccessException { String userNameDesc = "userName"; UserInfo userInfo = new UserInfo(); userInfo.setUserName("init"); BeanInfo beanInfo = Introspector.getBeanInfo(UserInfo.class); PropertyDescriptor[] proDescrtptors = beanInfo.getPropertyDescriptors(); if (proDescrtptors != null && proDescrtptors.length > 0) { for (PropertyDescriptor propDesc : proDescrtptors) { if (propDesc.getName().equals(userNameDesc)) { Method methodGetUserName = propDesc.getReadMethod(); Object objUserName = methodGetUserName.invoke(userInfo); System.out.println("get userName:" + objUserName.toString()); break; } } } } }
详细请参见:http://www.cnblogs.com/peida/archive/2013/06/03/3090842.html
public static <T> Map<String, Object> beanToMap(T bean) { Class<? extends Object> type = bean.getClass(); Map<String, Object> returnMap = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(type); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { String propertyName = descriptor.getName(); if (!propertyName.equals("userRoles") && !propertyName.equals("user")) { if (!propertyName.equals("class")) { Method readMethod = descriptor.getReadMethod(); Object result = readMethod.invoke(bean); returnMap.put(propertyName, result != null ? result : ""); } } } } catch (IntrospectionException e) { throw new RuntimeException("分析类属性失败", e); } catch (IllegalAccessException e) { throw new RuntimeException("分析类属性失败", e); } catch (InvocationTargetException e) { throw new RuntimeException("分析类属性失败", e); } return returnMap; } @Test public void test9764567() { UserInfo userInfo = new UserInfo(); userInfo.setUserName("lyx"); userInfo.setAge(12); userInfo.setEmailAddress("sdsdsd"); userInfo.setUserId(231323L); Map bean = beanToMap(userInfo); Set<Map.Entry<String, Object>> entrySet = bean.entrySet(); for (Map.Entry<String, Object> entry : entrySet) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); } }
=============END=============