views:

315

answers:

4

Hi. I have a class and i want to find all of it's public variables (not functions). how can i do so? thanks!

+1  A: 

You should be able to do this using Reflection API.

Crozin
+9  A: 
Field[] fields = YourClassName.class.getFields();

returns an array of all public variables of the class.

getFields() return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields(), and filter the public ones with the following Modifier approach:

Modifier.isPublic(field.getModifiers());

The YourClassName.class literal actually represents an object of type java.lang.Class. Check its docs for more interesting reflection methods.

The Field class above is java.lang.reflect.Field. You may take a look at the whole java.lang.reflect package.

Bozho
just a note - initially my answer contained a wrong statement, yet it was upvoted a number of times. Please read more carefully ;)
Bozho
@downvoter - the mistake was before. If you see one now, please share.
Bozho
+3  A: 

see this Excellent java reflection tutorial by ibm to get all the constructor , variables and even methods.

Ahmed Kotb
+1  A: 

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#getDeclaredFields%28%29

john
getDeclaredFields return private fields as well. Also, don't give links to 1.4.2 docs
Bozho