In Java, how do I get all the static fields in a typed list as objects of my class (and NOT as Field instances)?

I need to iterate over the list of static fields of a class (say MyClass ). These fields are of type java.util.regex.Pattern. Using reflection, I can get all the static fields as follows:

 MyClass mc = new MyClass(); List<Pattern> patternList = new ArrayList<Pattern>(); for (Field f : Commands.class.getDeclaredFields()) { if (Modifier.isStatic(f.getModifiers())) { // add the Pattern corresponding to the field f to the list patternList } } 

Now, since I know that all f fields are of type java.util.regex.Pattern, I want to create a List<Pattern> containing all of them. How can i do this?

I did not find a single question that would fit me, although there are a few questions about the thoughts. I apologize if my question is repeated.

+4
source share
1 answer

How about this?

 patternList.add((Pattern)f.get(null)); 

(As for the wording of your question, the field f is of type Field , but it has a target of type Pattern .)

Link: http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html

+3
source

All Articles