- /**
- * java反射bean的get方法
- *
- * @param objectClass
- * @param fieldName
- * @return
- */
- @SuppressWarnings("unchecked")
- public static Method getGetMethod(Class objectClass, String fieldName) {
- StringBuffer sb = new StringBuffer();
- sb.append("get");
- sb.append(fieldName.substring(0, 1).toUpperCase());
- sb.append(fieldName.substring(1));
- try {
- return objectClass.getMethod(sb.toString());
- } catch (Exception e) {
- }
- return null;
- }
- /**
- * java反射bean的set方法
- *
- * @param objectClass
- * @param fieldName
- * @return
- */
- @SuppressWarnings("unchecked")
- public static Method getSetMethod(Class objectClass, String fieldName) {
- try {
- Class[] parameterTypes = new Class[1];
- Field field = objectClass.getDeclaredField(fieldName);
- parameterTypes[0] = field.getType();
- StringBuffer sb = new StringBuffer();
- sb.append("set");
- sb.append(fieldName.substring(0, 1).toUpperCase());
- sb.append(fieldName.substring(1));
- Method method = objectClass.getMethod(sb.toString(), parameterTypes);
- return method;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 執行set方法
- *
- * @param o執行對象
- * @param fieldName屬性
- * @param value值
- */
- public static void invokeSet(Object o, String fieldName, Object value) {
- Method method = getSetMethod(o.getClass(), fieldName);
- try {
- method.invoke(o, new Object[] { value });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 執行get方法
- *
- * @param o執行對象
- * @param fieldName屬性
- */
- public static Object invokeGet(Object o, String fieldName) {
- Method method = getGetMethod(o.getClass(), fieldName);
- try {
- return method.invoke(o, new Object[0]);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
用JAVA Bean 反射得到set,get方法
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.