Sub topic 3
Inspecting fields, methods, constructors, and modifiers
This chapter assumes you can already obtain a Class object with .class, getClass(), or Class.forName(), as covered in the previous chapter. It also assumes you know basic Java classes and checked exceptions. Here you will list what a class contains and read its modifiers.
Two families of lookups
Each kind of member has two groups of methods on Class. The difference between the groups causes most beginner mistakes.
| Method | Returns | Includes inherited? | Includes non-public? |
|---|---|---|---|
| `getFields()` | fields | yes, from superclasses and interfaces | no, public only |
| `getDeclaredFields()` | fields | no | yes |
| `getMethods()` | methods | yes, including those from `Object` | no, public only |
| `getDeclaredMethods()` | methods | no | yes |
| `getConstructors()` | constructors | not applicable | no, public only |
| `getDeclaredConstructors()` | constructors | not applicable | yes |
Constructors are never inherited, so no Class method returns a superclass's constructors. If you want a class's own members of any visibility, use the getDeclared... methods. If you want what callers can use, including inherited members, use the plain ones.
A first inspection
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
class Account {
public static final String BANK = "Demo";
private double balance;
protected String owner;
public Account() {
}
private Account(double balance) {
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
private void audit() {
}
}
public class InspectMembers {
public static void main(String[] args) {
Class<?> c = Account.class;
for (Field f : c.getDeclaredFields()) {
System.out.println("field " + Modifier.toString(f.getModifiers())
+ " " + f.getType().getSimpleName() + " " + f.getName());
}
for (Method m : c.getDeclaredMethods()) {
System.out.println("method " + Modifier.toString(m.getModifiers())
+ " " + m.getReturnType().getSimpleName() + " " + m.getName()
+ " params=" + m.getParameterCount());
}
for (Constructor<?> k : c.getDeclaredConstructors()) {
System.out.println("ctor " + Modifier.toString(k.getModifiers())
+ " " + Arrays.toString(k.getParameterTypes()));
}
}
}The program prints three fields, two methods, and two constructors. The Java specification does not guarantee the order of the results. Do not rely on declaration order.
Reading modifiers
getModifiers() returns an int that packs the modifier flags into bits. You can turn it into text with Modifier.toString(int). You can also test a single flag with a helper such as Modifier.isPrivate(m.getModifiers()) or Modifier.isStatic(...).
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
class Config {
public static final int LIMIT = 10;
private String name;
}
public class ModifierDemo {
public static void main(String[] args) throws Exception {
for (Field f : Config.class.getDeclaredFields()) {
int mods = f.getModifiers();
System.out.println(f.getName()
+ " static=" + Modifier.isStatic(mods)
+ " final=" + Modifier.isFinal(mods)
+ " private=" + Modifier.isPrivate(mods));
}
}
}Looking up one specific member
When you know the name, ask for it directly: getDeclaredField("balance"), getMethod("deposit", double.class), or getDeclaredConstructor(double.class). For methods and constructors, you must pass the parameter types exactly. Use double.class, not Double.class, for a primitive parameter.
A failed lookup throws a checked exception, either NoSuchFieldException or NoSuchMethodException.
Common errors
- Using
getMethods()and expecting to see private methods. It returns only public ones. - Using
getDeclaredMethods()and expecting inherited methods. It returns only methods declared in that class. - Passing the wrong parameter type, such as
Double.classfor adoubleparameter. This throwsNoSuchMethodException. - Expecting
getDeclaredMethods()to list only your code. The compiler can add synthetic members, such as lambda bodies. Checkm.isSynthetic()if you need to filter them out.
Exercise
A class Base declares a public method run(). A class Child extends Base declares no methods. What does Child.class.getDeclaredMethods().length return, and how does Child.class.getMethods() differ?
Show answer
getDeclaredMethods() returns 0, because Child declares nothing itself. getMethods() includes the inherited public run() plus the public methods inherited from Object, such as toString() and hashCode().