Java Rereflection:查找字段的名称和值 [英] Java Refelection : find field's name and value
问题描述
我上课
如下所示
public class SampleReflection {
public static final String TWO_name = "html";
public static final String TWO_find = "css";
public static final String ONE_KEY_java = "java";
public static final String ONE_KEY_jsp = "jsp";
public static final String ONE_KEY_oracle = "oracle";
public static final String ONE_KEY_spring = "spring";
public static final String ONE_KEY_struts = "struts";
}
我想获取所有以 ONE_KEY
开头的字段及其值.
I would like to get all the fields which starts with ONE_KEY
and their value.
因为 ONE_KEY_xxx
可以是任何数字.
如何在Java反射中或在Java中以其他方式执行此操作?
how to do this in java reflection or any other way in java ?
谢谢
推荐答案
您可以使用 SampleReflection.class.getDeclaredFields()
,遍历结果并按名称过滤.然后调用 field.get(null)
以获取静态字段的值.如果还要访问非公共字段,则可能必须调用 first.setAccessible(true)
(前提是安全管理器允许这样做).
You can use SampleReflection.class.getDeclaredFields()
, iterate over the result and filter by name. Then call field.get(null)
to get the value of the static fields. If you want to access non-public fields as well you might have to call first.setAccessible(true)
(provided the security manager allows that).
或者,您可以查看Apache Common的反射实用程序,例如 FieldUtils
之类.
Alternatively you could have a look at Apache Common's reflection utilities, e.g. FieldUtils
and the like.
根据您实际想要实现的目标,可能会有更好的方法,例如使用地图,枚举等.
Depending on what you actually want to achieve there might be better approaches though, e.g. using a map, enums etc.
在您拥有静态字段的情况下,使用枚举可能是一种更好的方法.示例:
In your case where you have static fields using an enum might be a better way to go. Example:
enum SampleFields {
TWO_name("html"),
TWO_find("css"),
ONE_KEY_java("java"),
ONE_KEY_jsp("jsp");
ONE_KEY_oracle("oracle"),
...;
private String value;
private SampleFields(String v) {
value = v;
}
}
然后遍历 SampleFields.values()
并按名称进行过滤.
Then iterate over SampleFields.values()
and filter by name.
或者,如果满足您的需要,则可以拆分名称,然后将映射传递给枚举值,例如
Alternatively, if that fits your needs, you could split the names and pass a map to the enum values, e.g.
enum SampleFields {
TWO(/*build a map "name"->"html","find"->"css")*/ ),
ONE_KEY(/*build a map "java"->"java","jsp"->"jsp", ...*/);
private Map<String, String> values;
private SampleFields(Map<String, String> map) {
values = map;
}
}
然后获取如下枚举值: SampleFields.valueOf("ONE_KEY").get("java")
Then get the enum values like this: SampleFields.valueOf("ONE_KEY").get("java")
这篇关于Java Rereflection:查找字段的名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!