package com.shell.reflecttest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainApp {
public static void main(String[] args) {
User user = new User();
user.setId(1);
user.setName("myname");
user.setAge(27);
System.out.println(getValueByFieldName("age", user));
}
public static Object getValueByFieldName(String fieldName, Object obj) {
String methodString = getMethodStringByFieldString(fieldName);
Object object = null;
try {
Method method = User.class.getMethod(methodString, null);
object = method.invoke(obj, null);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public static String getMethodStringByFieldString(String fieldString) {
StringBuffer buffer = new StringBuffer(fieldString);
buffer.replace(0, 1, buffer.substring(0, 1).toUpperCase());
buffer.insert(0, "get");
return buffer.toString();
}
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainApp {
public static void main(String[] args) {
User user = new User();
user.setId(1);
user.setName("myname");
user.setAge(27);
System.out.println(getValueByFieldName("age", user));
}
public static Object getValueByFieldName(String fieldName, Object obj) {
String methodString = getMethodStringByFieldString(fieldName);
Object object = null;
try {
Method method = User.class.getMethod(methodString, null);
object = method.invoke(obj, null);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return object;
}
public static String getMethodStringByFieldString(String fieldString) {
StringBuffer buffer = new StringBuffer(fieldString);
buffer.replace(0, 1, buffer.substring(0, 1).toUpperCase());
buffer.insert(0, "get");
return buffer.toString();
}
}