Get Field
Using Java Reflection you can inspect the fields (member variables) of classes and get / set them at runtime.
This is done via the Java class java.lang.reflect.Field.
This text will get into more detail about the Java Field object. You can access the fields (member variables) of a class like this:
Field[] method = aClass.getFields();
-
Remember to check the JavaDoc from Sun out too. Here is a list of
the topics covered:
- Obtaining Field Objects
- Field Name
- Field Type
- Getting and Setting Field Values
1)Obtaining Field Objects:
The Field class is obtained from the Class object.example:
Class aClass = ...//obtain class object
Field[] methods = aClass.getFields();
The Field[] array will have one Field instance for each
public field declared in the class.Field[] methods = aClass.getFields();
If you know the name of the field you want to access, you can access it like this:-
Class aClass = MyObject.class
Field field = aClass.getField("someField");
The example above will return the Field instance corresponding to the
field someFieldas declared in the MyObject below:Field field = aClass.getField("someField");
public class MyObject{ public String
someField = null; }
If no field exists with the name given as parameter to the getField()
method, aNoSuchFieldException is thrown.
2)Field Name:
Once you have obtained a Field instance, you can get its field name using theField.getName() method, like this:Field field = ... //obtain field object
String fieldName = field.getName();
3)Field Type:
You can determine the field type (String, int etc.) of a field using the Field.getType()method:
Field field = aClass.getField("someField");
Object fieldType = field.getType();
Object fieldType = field.getType();
4)Getting and Setting Field Values
Once you have obtained a Field reference you can get and set its values using theField.get() and Field.set()methods, like this:
Class aClass = MyObject.class
Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);
The objectInstance parameter passed to the get and set method should
be an instance of the class that owns the field. In the above example
an instance of MyObject is used, because the someField is an instance
member of the MyObject class.Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);
It the field is a static field (public static ...) pass null as parameter to the get and setmethods, instead of the objectInstance parameter passed above.


