提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
在Java Bean上调用Get方法
/* 来 自* n o w j a v a . c o m */ //package com.nowjava; import java.lang.reflect.Method; public class Main { public static void main(String[] argv) throws Exception { Object o = "nowjava.com"; String fieldName = "nowjava.com"; System.out.println(invokeGet(o, fieldName)); } public static Object invokeGet(Object o, String fieldName) { Method method = getGetMethod(o.getClass(), fieldName);/* 来 自 NowJava.com - 时 代 Java*/ try { return method.invoke(o, new Object[0]); } catch (Exception e) { e.printStackTrace(); } return null; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static Method getGetMethod(Class objectClass, String fieldName) { StringBuffer sb = new StringBuffer(); sb.append("get"); sb.append(fieldName.substring(0, 1).toUpperCase());