java类的静态属性值获取

时间:2023-01-30 05:59:29

获取某个类实例的静态属性:

public class ErrorCode {

    private String code;
private String message; private ErrorCode(String code, String message) {
this.code = code;
this.message = message;
} public String getCode() {
return code;
} public String getMessage() {
return message;
} public static final ErrorCode 交易成功 = new ErrorCode("00000", "交易成功");
public static final ErrorCode 交易失败 = new ErrorCode("00001", "交易失败");
}

遍历获取其静态属性的code和message:

public static void main(String[] args) throws Exception {
Class<?> ownerClass = Class.forName("com.kayak.frame.ErrorCode");
Field[] fields = ErrorCode.class.getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
Object o = field.get(ownerClass);
ErrorCode e = (ErrorCode) o;
System.out.println(e.getCode() + " " + e.getMessage());
}
}
}

打印结果:

00000 交易成功
00001 交易失败

如果获取指定的静态属性:

/**
* 得到某个类的静态属性 java反射机制
*
* @param className
* @param fieldName
* @return
* @throws Exception
*/
public Object getStaticProperty(String className, String fieldName)
throws Exception {
Class ownerClass = Class.forName(className); Field field = ownerClass.getField(fieldName); Object property = field.get(ownerClass); return property;
}