|
Java™ by example!
|
|
|
How do I get a list of all declared fields and values in an Object?
Use the reflection API. It allows you to inspect class members at runtime. The process is simple: get the classname from the class you want to inspect and invoke getDeclaredFields. This will give you an array of member variables that have been declared in that object. To get the actual value, call the get method on a field instance with the object you want to inspect. You are not allowed to inspect private values, unless you specifically ask for it (see second example). Person.java (the class we are inspecting)
Main.java
Running this program will yield:
As the integer "age" is declared as being private to the class, the Java Runtime Environment will throw an IllegalAccessException. However, since Java 2, a new function has been added to the Field class that solves this problem. Invoke setAccessible(true) on a field that is private, and you'll get the value.
outputs:
See the Reflection API for more functionality.
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|