Java反射获取类的属性值

来源:互联网 发布:qq飞升坐骑升阶数据 编辑:程序博客网 时间:2024/05/17 18:26
public class ReflectUtil {

private static final String CHARSET ="UTF-8";

// 把一个字符串的第一个字母大写、效率是最高的、
public static String getMethodName(String fildeName) throws Exception{
byte[] items = fildeName.getBytes(CHARSET);
items[0] = (byte) ((char) items[0] - 'a' + 'A');
return new String(items, CHARSET);
}

public static Object getObjevtValue(Object object, String property) throws Exception {
if(object != null) {
Class<?> clz = object.getClass();

Field field = clz.getDeclaredField(property);//获取属性名
Method method = object.getClass().getMethod("get" + getMethodName(field.getName()), new Class[]{});//获取get方法

return method.invoke(object);//通过get方法获取属性值,返回属性值
}
return null;
}
}
0 0
原创粉丝点击