Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all variable names in a class

I have a class and I want to find all of its public fields (not methods). How can I do this?

like image 380
ufk Avatar asked Jan 24 '10 10:01

ufk


People also ask

How do you get all variables in a class?

Field[] fields = YourClassName. class. getFields(); returns an array of all public variables of the class.

How to get all the field names of a class in Java?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How to get variable names in Java?

The name of the variable should begin with either alphabet or, an underscore (_) or, a dollar ($) sign. The identifiers used for variables must not be keywords. No spaces or special characters are allowed in the variable names of Java. Variable names may contain 0 to 9 numbers (if not at the beginning).

How to get fields of a class in Java?

In JavaSW, it's easy to list the declared fields of a class. If you have an object, you can obtain its Class object by calling getClass() on the object. You can then call getDeclaredFields() on the Class object, which will return an array of Field objects. This list can include public, protected, and private fields.


1 Answers

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.

like image 175
Bozho Avatar answered Oct 11 '22 22:10

Bozho