I am trying to learn about reflection and obtain fields as follows:
Class<?> inputClass = in.getClass();
Field[] classFields = inputClass.getFields();
The code is fine up to this point. Now I want to go through each of the fields, printing their value, so I do:
for (Field f : classFields) {
System.out.println(f.get(new Object()).toString());
}
with an appropriate try/catch for an IllegalAccessException (omitted for clarity). I have also tried passing in a String here, which also yields the result described below. Every f has a type that is not Object, String, or equal to that of in.
This throws the exception:
Exception in thread "Thread-0" java.lang.IllegalArgumentException: Can not set java.lang.String field TestClass.testField to java.lang.Object
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:372)
at LearningReflection.messageToText(LearningReflection.java:88)
at LearningReflection$1.run(LearningReflection.java:180)
I'm guessing this is because I've passed an instance of Object (or String, when I replaced Object with String), rather than an instance of the particular subclass of Object that the class actually contains. Since I don't know what this will be at compile time, I need to extract information from the field as to the type of the class and instantiate it at runtime to pass to the get() method. Is this guess correct, and if so, how do I go about doing this?