();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; }}
为了代码清楚些,将⼀些⼯具⽅法独⽴⼀下,如field name到getter name的转换⽅法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; }
}
⼤功告成
现在,写个VO作为模拟数据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; }}
最后,测试类,此类将直接调⽤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 map = FieldsCollector.getFileds(user); System.out.println(map);}}
Oh year, 成功了~~~
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。