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=============