用反射获取类中的属性值
根据其中一个变量的值,获取另外一个变量的值,此处用于根据自定义代码获取自定义代码名称
public static String catchCode(String code) throws Exception {
Class tb = Constant.class;
Field[] f = Constant.class.getDeclaredFields();
String result = "未知异常!";
boolean flag = false;
for (int i = 0; i < f.length; i++) {
f[i].setAccessible(true);
if (f[i].get(tb).equals(code)) {
result = f[i].getName();
result = result + "_NAME";
for (int j = 0; i < f.length; j++) {
f[j].setAccessible(true);
if (f[j].getName().equals(result)) {
result=(String) f[j].get(tb);
flag = true;
break;
}
}
}
if (flag) {
break;
}
}
return result;
}
public interface Constant {
//登录异常代码
public static final String LOGIN_CODE_1 = "1001";
public static final String LOGIN_CODE_1_NAME = "帐号或密码错误";
public static final String LOGIN_CODE_2 = "1002";
public static final String LOGIN_CODE_2_NAME = "您的帐号已经锁定,请联系系统管理员";
public static final String LOGIN_CODE_3 = "1003";
public static final String LOGIN_CODE_3_NAME = "您的帐号已经过期,请联系系统管理员";
public static final String LOGIN_CODE_4 = "1004";
public static final String LOGIN_CODE_4_NAME = "系统出现意外,请稍后登录";
}