您好,登錄后才能下訂單哦!
這篇文章主要介紹了Java反射通過(guò)Getter方法獲取對(duì)象VO的屬性值過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
有時(shí)候,需要?jiǎng)討B(tài)獲取對(duì)象的屬性值。
比如,給你一個(gè)List,要你遍歷這個(gè)List的對(duì)象的屬性,而這個(gè)List里的對(duì)象并不固定。比如,這次User,下次可能是Company。
e.g. 這次我需要做一個(gè)Excel導(dǎo)出的工具類(lèi),導(dǎo)出的批量數(shù)據(jù)是以List類(lèi)型傳入的,List里的對(duì)象自然每次都不同,這取決于需要導(dǎo)出什么信息。
為了使用方便,將對(duì)象的屬性名與屬性值存于Map當(dāng)中,使用時(shí)就可以直接遍歷Map了。
此次的思路是通過(guò)反射和Getter方法取得值,然后記錄在一個(gè)Map當(dāng)中。
Kick start...
將對(duì)象的屬性名與屬性值存于Map當(dāng)中,以key,value的形式存在,而value并不希望以單一類(lèi)型(如String)存在(因?yàn)樯婕岸喾N類(lèi)型),所以用一個(gè)FieldEntity的自定義類(lèi)(此類(lèi)包含屬性名,屬性值,屬性值類(lèi)型 等屬性)
FieldEntity
package com.nicchagil.util.fields; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class FieldsCollector { public static Map<String, FieldEntity> getFileds(Object object) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); Map<String, FieldEntity> map = new HashMap<String, FieldEntity> (); for (int i = 0; i < fields.length; i++) { Object resultObject = invokeMethod(object, fields[i].getName(), null); map.put(fields[i].getName(), new FieldEntity(fields[i].getName(), resultObject, fields[i].getType())); } return map; } public static Object invokeMethod(Object owner, String fieldname, Object[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class ownerClass = owner.getClass(); Method method = null; method = ownerClass.getMethod(GetterUtil.toGetter(fieldname)); Object object = null; object = method.invoke(owner); return object; } }
主類(lèi),通過(guò)這個(gè)類(lèi)的靜態(tài)方法獲取結(jié)果Map
FieldsCollector
package com.nicchagil.util.fields; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class FieldsCollector { public static Map<String, FieldEntity> getFileds(Object object) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); Map<String, FieldEntity> map = new HashMap<String, FieldEntity> (); for (int i = 0; i < fields.length; i++) { Object resultObject = invokeMethod(object, fields[i].getName(), null); map.put(fields[i].getName(), new FieldEntity(fields[i].getName(), resultObject, fields[i].getType())); } return map; } public static Object invokeMethod(Object owner, String fieldname, Object[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Class ownerClass = owner.getClass(); Method method = null; method = ownerClass.getMethod(GetterUtil.toGetter(fieldname)); Object object = null; object = method.invoke(owner); return object; } }
為了代碼清楚些,將一些工具方法獨(dú)立一下,如field name到getter name的轉(zhuǎn)換方法
GetterUtil
package com.nicchagil.util.fields; public class GetterUtil { /** * Get getter method name by field name * @param fieldname * @return */ public static String toGetter(String fieldname) { if (fieldname == null || fieldname.length() == 0) { return null; } /* If the second char is upper, make 'get' + field name as getter name. For example, eBlog -> geteBlog */ if (fieldname.length() > 2) { String second = fieldname.substring(1, 2); if (second.equals(second.toUpperCase())) { return new StringBuffer("get").append(fieldname).toString(); } } /* Common situation */ fieldname = new StringBuffer("get").append(fieldname.substring(0, 1).toUpperCase()) .append(fieldname.substring(1)).toString(); return fieldname; } }
大功告成?。?!
現(xiàn)在,寫(xiě)個(gè)VO作為模擬數(shù)據(jù)
User
import java.util.Date; public class User { private String username; private String password; private String eBlog; private Date registrationDate; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String geteBlog() { return eBlog; } public void seteBlog(String eBlog) { this.eBlog = eBlog; } public Date getRegistrationDate() { return registrationDate; } public void setRegistrationDate(Date registrationDate) { this.registrationDate = registrationDate; } }
最后,測(cè)試類(lèi),此類(lèi)將直接調(diào)用FieldsCollector~~
Call
import java.util.Date; import java.util.Map; import com.nicchagil.util.fields.FieldEntity; import com.nicchagil.util.fields.FieldsCollector; public class Call { public static void main(String[] args) throws Exception { User user = new User(); user.setUsername("user109"); user.setPassword("pwd109"); user.seteBlog("http://www.cnblogs.com/nick-huang/"); user.setRegistrationDate(new Date()); Map<String, FieldEntity> map = FieldsCollector.getFileds(user); System.out.println(map); } }
Oh year, 成功了~~~
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。