Similar to this question, I need to access all the private fields of one instance of a POJO. The difference is that I don't know the specific name(s) of the field(s) I want ahead of time.
For example, if my POJO is:
public class Widget {
private java.lang.String fizz;
private java.lang.Boolean buzz;
private com.me.myapp.Foo foo;
}
I'm looking for some way of inspecting a Widget
instance (or the class itself) and seeing that it has those 3 fields/types, without knowing their names/types ahead of time.
Is this possible? If so, how? If not, why?
Update:
System.out.println("classToInspect = " + classToInspect.getName() + ", and fields are:\n");
for(Field f : allFields)
System.out.println(f.getType());
Prints:
classToInspect = com.myorg.myapp.LoggerConfig, and fields are:
int
int
int
class java.lang.reflect.Constructor
class java.lang.Class
class java.lang.String
class java.security.ProtectionDomain
boolean
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
class java.lang.ref.SoftReference
int
int
class sun.reflect.generics.repository.ClassRepository
long
class [Ljava.io.ObjectStreamField;
class sun.reflect.ReflectionFactory
boolean
class [Ljava.lang.Object;
interface java.util.Map
class [Ljava.lang.annotation.Annotation;
interface java.util.Map
interface java.util.Map
class sun.reflect.annotation.AnnotationType
Please note: none of these fields are fields/properties/members of my actual LoggerConfig
class; they must be provided/added through reflection or a part of the Object
super class...