import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 操作class的相关
* @author liugang
*
*/
public class ClassUtil {
/**
* 根据class的路径字符串生成实例
* @param className class的路径字符串
* @return
*/
public static Object getClass(String className) {
Object o=null;
try{
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
if (classLoader == null) {
classLoader = ClassUtil.class.getClassLoader();
}
Class<?> c=classLoader.loadClass(className);
o=c.newInstance();
}catch (Exception e){
System.out.println(e.getMessage());
}
return o;
}
/**
* 根据类的字段名返回对应的值
* @param o 要操作的object
* @param fieldName 字段名
* @return 对应字段名的对象
*/
public static Object getData(Object o,String fieldName){
Object oRet=null;
try{
Class<?> c=o.getClass();
Field f=c.getDeclaredField(fieldName);
f.setAccessible(true);
oRet=f.get(o);
}catch(Exception e){
//System.out.println(e.getMessage());
return null;
}
return oRet;
}
/**
* 从object中取对应的字段名的value(字段必须存在get方法)
* @param o
* @param fieldName
* @return 返回字符串,非字符串的字段不能取到
*/
public static String getDataByGet(Object o,String fieldName){
String ss="";
try{
Class<?> ownerClass = o.getClass();
Class<?>[] arges = null;
Object[] objs = null;
Method method = ownerClass.getMethod(getGetMethodName(fieldName), arges);
Object oo=method.invoke(o, objs);
if (oo != null) {
if (oo instanceof String) {
ss = ((String) oo).trim();
}
}
}catch (Exception e){
return "";
}
return ss;
}
private static String getGetMethodName(String field) {
return "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
}