4

I need to iterate through a list of static fields of a class (say, MyClass). These fields are all of the 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 the fields f are of the type java.util.regex.Pattern, I want to create a List<Pattern> containing all of them. How can I do that?

I haven't found any question that matches mine, although there are several questions on SO about reflection. I apologize if my question is a repetition.

3
  • Thanks for doing 90% of the work in your question. =) Commented Mar 16, 2013 at 21:35
  • I like to work hard in search of an answer before I ask for help on SO. People such as yourself make this place a center of intellectual joy :) Commented Mar 16, 2013 at 21:51
  • To those who marked this as duplicate, PLEASE READ THE QUESTION FIRST. It is NOT the same as the question that has been linked with "This question already has an answer here". That question simply wants the Field objects, while I want to retrieve the original object. Commented Apr 1, 2013 at 13:42

1 Answer 1

3

How about this?

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

(Regarding the phrasing of your question, the field f is of type Field, but it has a target that has type Pattern.)

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

Sign up to request clarification or add additional context in comments.

12 Comments

The Field class doesn't seem to have any method called get(). And, of course, a Field object cannot be casted into Pattern directly, so (Pattern) f is not possible.
I think you need to supply a null argument to the get call. If it were an instance field, the argument would be a reference to the target object.
I have edited the answer to use get(null). Would you need an explanation of how that works?
Also, @ChthonicProject Nayuki didn't write (Pattern)f. He wrote (Pattern) f.get(), which means the downcast applies to the result of f.get().
So naturally, you want to call get() to get the value of the field, right? Not so quick. If the field is static, like Math.PI, then it only has one value. But if the field wasn't static, like (hypothetically) myString.length, then the field needs to be associated with an instance. So you would call f.get(myString) to mean the same as myString.length.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.