esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

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)

This code sample is only viewable to esus.com members
Login or become a member!


Main.java

This code sample is only viewable to esus.com members
Login or become a member!


Running this program will yield:

This code sample is only viewable to esus.com members
Login or become a member!


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.

This code sample is only viewable to esus.com members
Login or become a member!


outputs:

This code sample is only viewable to esus.com members
Login or become a member!


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!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.