Sub topic 3
Inspecting fields, methods, constructors, and modifiers
This chapter assumes you can already get a Class object with .class, getClass(), or Class.forName(), and that you know core Java: fields, methods, constructors, access modifiers, and checked exceptions. Here you will use a Class object to list what a type declares and to read each member's modifiers, types, and parameters. Later chapters use these members to create objects and to read, write, and call them.
The member types
A Class object describes a type. It hands out three kinds of member objects, all from java.lang.reflect:
Fielddescribes a field.Methoddescribes a method.Constructor<T>describes a constructor.
All three implement the Member interface, which provides getName(), getModifiers(), and getDeclaringClass(). Each also extends AccessibleObject, which provides setAccessible, covered in a later chapter.
Declared versus public members
Each kind of member has two families of lookup methods. The difference between them causes most beginner confusion.
| Method | Returns | Includes inherited members | Includes non-public members |
|---|---|---|---|
| `getFields()` | all fields | yes | no, public only |
| `getDeclaredFields()` | all fields | no | yes |
| `getMethods()` | all methods | yes | no, public only |
| `getDeclaredMethods()` | all methods | no | yes |
| `getConstructors()` | all constructors | not applicable | no, public only |
| `getDeclaredConstructors()` | all constructors | not applicable | yes |
Constructors are never inherited, so the two constructor methods differ only in visibility.
The "declared" methods answer the question "what did this exact class write in its source?" The plain methods answer the question "what can a caller use on this type?" The second answer includes public members from superclasses and interfaces. For getMethods() it also includes the public methods of Object.
Listing a class's members
The program below prints each member's modifiers, type, and name. The target class has one member of each visibility, so you can see how the modifiers print.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;
class Account {
public static final String CURRENCY = "EUR";
private final String owner;
protected double balance;
public Account(String owner) {
this(owner, 0);
}
Account(String owner, double balance) {
this.owner = owner;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
}
private void audit() {
System.out.println(owner + " " + balance);
}
public static Account of(String owner) {
return new Account(owner);
}
}
public class MemberInspector {
static String mods(int modifiers) {
String s = Modifier.toString(modifiers);
return s.isEmpty() ? "" : s + " ";
}
static String params(Class<?>[] types) {
return Arrays.stream(types)
.map(Class::getSimpleName)
.collect(Collectors.joining(", "));
}
public static void main(String[] args) {
Class<?> type = Account.class;
Field[] fields = type.getDeclaredFields();
Arrays.sort(fields, Comparator.comparing(Field::getName));
for (Field f : fields) {
System.out.println(mods(f.getModifiers())
+ f.getType().getSimpleName() + " " + f.getName());
}
Constructor<?>[] ctors = type.getDeclaredConstructors();
Arrays.sort(ctors, (a, b) ->
Integer.compare(a.getParameterCount(), b.getParameterCount()));
for (Constructor<?> c : ctors) {
System.out.println(mods(c.getModifiers())
+ type.getSimpleName() + "(" + params(c.getParameterTypes()) + ")");
}
Method[] methods = type.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName));
for (Method m : methods) {
System.out.println(mods(m.getModifiers())
+ m.getReturnType().getSimpleName() + " " + m.getName()
+ "(" + params(m.getParameterTypes()) + ")");
}
}
}The output is:
public static final String CURRENCY
protected double balance
private final String owner
public Account(String)
Account(String, double)
private void audit()
public void deposit(double)
public static Account of(String)The program sorts every array before printing.
Reading modifiers
getModifiers() returns an int in which each modifier is one bit. Do not compare it to constants yourself. Use the static helpers in java.lang.reflect.Modifier:
Modifier.isPublic(int),isPrivate,isProtectedModifier.isStatic,isFinal,isAbstractModifier.isSynchronized,isVolatile,isTransient,isNativeModifier.toString(int), which produces text such aspublic static final
A package-private member has no access bit set, so Modifier.toString returns an empty string for it. That is why the Account(String, double) constructor printed with no prefix.
A common task is to find only the instance fields:
for (Field f : type.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers())) {
System.out.println(f.getName());
}
}Class has its own getModifiers(), which also reports interface and abstract for types. The isInterface(), isEnum(), isArray(), and isPrimitive() methods answer the other common questions about a type.
Types, parameters, and exceptions
Each member object also describes the types it uses:
Field.getType()returns the declared type as aClass<?>.Method.getReturnType()returns the return type, andvoid.classfor a method that returns nothing.getParameterTypes()andgetParameterCount()are available on bothMethodandConstructor.getExceptionTypes()lists the declaredthrowsclause.isVarArgs()reports whether the last parameter is a varargs parameter.
getType() returns the raw class. For List<String> it returns List. The generic form comes from getGenericType(), which a later chapter covers.
By default, Parameter objects from getParameters() report names such as arg0 and arg1. The compiler stores real parameter names only when you compile with javac -parameters. Do not rely on parameter names unless you control the build.
Looking up one member by name
When you know what you want, ask for a single member:
getDeclaredField("balance")andgetField("CURRENCY")getDeclaredMethod("deposit", double.class)andgetMethod("deposit", double.class)getDeclaredConstructor(String.class)andgetConstructor(String.class)
A method is identified by its name and its parameter types together, because Java allows overloads. Pass double.class, not Double.class, for a double parameter. The two are different classes.
A failed lookup throws a checked exception: NoSuchFieldException for fields and NoSuchMethodException for methods and constructors. The scope also matters for single lookups. getDeclaredMethod does not search superclasses, so asking Child.class for a method that only Base declares fails. getMethod does search superclasses, but only among public methods.
The next program shows the scope difference with a base class and a subclass:
import java.lang.reflect.Method;
import java.util.Arrays;
class Base {
public void a() { }
private void b() { }
}
class Child extends Base {
public void c() { }
}
public class ScopeDemo {
static String[] names(Method[] methods) {
return Arrays.stream(methods)
.filter(m -> m.getDeclaringClass() != Object.class)
.map(Method::getName)
.sorted()
.toArray(String[]::new);
}
public static void main(String[] args) {
System.out.println("getMethods on Child: "
+ Arrays.toString(names(Child.class.getMethods())));
System.out.println("getDeclaredMethods on Child: "
+ Arrays.toString(names(Child.class.getDeclaredMethods())));
System.out.println("getDeclaredMethods on Base: "
+ Arrays.toString(names(Base.class.getDeclaredMethods())));
}
}The output is:
getMethods on Child: [a, c]
getDeclaredMethods on Child: [c]
getDeclaredMethods on Base: [a, b]The private method b never appears for Child. Reaching it means asking Base.class directly. A tool that must see the whole hierarchy, including private members, has to walk upward with getSuperclass() and call getDeclaredFields() on each class in turn.
Synthetic and bridge members
The compiler sometimes adds members that do not appear in your source. isSynthetic() reports compiler-generated members, and Method.isBridge() reports bridge methods. A bridge method is a generated method that makes generics and covariant return types work at the bytecode level.
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
class Box implements Comparable<Box> {
@Override
public int compareTo(Box other) {
return 0;
}
}
public class BridgeDemo {
public static void main(String[] args) {
Method[] methods = Box.class.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(
m -> m.getParameterTypes()[0].getSimpleName()));
for (Method m : methods) {
System.out.println(m.getName() + "("
+ m.getParameterTypes()[0].getSimpleName()
+ ") bridge=" + m.isBridge());
}
}
}The output is:
compareTo(Box) bridge=false
compareTo(Object) bridge=trueYou wrote one method, but the class declares two. The compareTo(Object) bridge is what the Comparable interface actually calls, and it forwards to compareTo(Box). Frameworks that scan methods usually skip bridge and synthetic members, because otherwise they process the same logical method twice. Inner classes also gain synthetic members, such as a field that refers to the enclosing instance.
Exercise
A class Config declares private int timeout; and extends Base, which declares protected int retries;. What does Config.class.getFields() return, and how would you find both fields by name?
Show answer
getFields() returns only public fields, so it returns an empty array here, because neither field is public. Config.class.getDeclaredField("timeout") finds the first field, since it is declared directly on Config. getDeclaredField("retries") on Config.class throws NoSuchFieldException, because getDeclaredField does not search superclasses. To find retries, call getDeclaredField("retries") on Base.class, or walk up the hierarchy with getSuperclass() and try each class in turn.
Exercise
Write a loop that prints the names of all non-static, non-synthetic declared methods of a class type, and explain why the printed order may change between JVMs.
Show answer
Use for (Method m : type.getDeclaredMethods()) { int mods = m.getModifiers(); if (!Modifier.isStatic(mods) && !m.isSynthetic()) { System.out.println(m.getName()); } }. The order may change because the Class API does not specify the order of the returned array. It depends on how the JVM reads the class file. Sort by name first if you need stable output.