I have a class
like below
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";
}
I would like to get all the fields which starts with ONE_KEY
and their value.
because the ONE_KEY_xxx
can be of any numbers.
how to do this in java reflection or any other way in java ?
thanks
You can use
SampleReflection.class.getDeclaredFields()
, iterate over the result and filter by name. Then callfield.get(null)
to get the value of the static fields. If you want to access non-public fields as well you might have to callfirst.setAccessible(true)
(provided the security manager allows that).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:
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.
Then get the enum values like this:
SampleFields.valueOf("ONE_KEY").get("java")
Thanks for the answer,
this is what i was looking for,