Java Reference
In-Depth Information
The
getFields()
method returns all the accessible public fields of the class or interface. The accessible public
fields include public fields declared in the class or inherited from the superclass. The
getDeclaredFields()
method
returns all the fields that appear in the declaration of the class. It does not include inherited fields. The other two
methods,
getField()
and
getDeclaredField()
, are used to get the
Field
object if you know the name of the field.
Let's consider the following declarations of classes
A
and
B
, and an interface
IConstants
:
interface IConstants {
int DAYS_IN_WEEK = 7;
}
class A implements IConstants {
private int aPrivate;
public int aPublic;
protected int aProtected;
}
class B extends A {
private int bPrivate;
public int bPublic;
protected int bProtected;
}
If
bClass
is the reference of the
Class
object for class
B
, the expression
bClass.getFields()
will return the
following three fields that are accessible and
public
:
public int B.bPublic
•
public int A.aPublic
•
public static final int IConstants.DAYS_IN_WEEK
•
However,
bClass.getDeclaredFields()
will return all three fields that are declared in class
B
.
private int B.bPrivate
•
public int B.bPublic
•
protected int B.bProtected
•
To get all the fields of a class and its superclass, you must get the reference of the superclass using the
getSuperclass()
method and use the combinations of these methods. Listing 3-5 illustrates how to get the
information about the fields of a class. Note that you do not get anything when you call the
getFields()
method on
the
Class
object of the
Person
class because there are no
public
fields that are accessible through the
Person
class.
Listing 3-5.
Reflecting on Fields of a Class
// FieldReflection.java
package com.jdojo.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
public class FieldReflection {
public static void main(String[] args) {
Class<Person> c = Person.class;