Class, Fields, and Methods
Fields, methods, and constructors are represented by objects too
Once you have a Class<?>, you can inspect the type's members.
Reflection uses separate objects for this: Field for a field,
Method for a method, and Constructor<?> for a constructor.
They describe a member's structure: its name, type, parameters, modifiers, and available annotations.
for (Method method : String.class.getDeclaredMethods()) {
System.out.println(method.getName());
}
Here, the program does not invoke String methods; it obtains their descriptions and reads their names.
The same approach works with fields and constructors.
get... and getDeclared...
Reflection makes an important distinction between two groups of methods. For example,
getMethods() returns public methods of the type, including applicable inherited ones,
while getDeclaredMethods() returns methods declared directly in that class or interface,
regardless of access level, but without inherited methods.
The same idea applies to fields and constructors: the API method you choose depends on whether you want the type's public surface or its own declaration specifically.
class Account {
private long id;
public String owner() { return "Ann"; }
}
Field[] fields = Account.class.getDeclaredFields();
Method[] methods = Account.class.getDeclaredMethods();
Finding a specific member
When the name and signature are known, there is no need to iterate over an array. You can request a specific method or constructor and explicitly provide its parameter types.
Method method = String.class.getMethod("substring", int.class);
Constructor<StringBuilder> constructor =
StringBuilder.class.getConstructor(int.class);
Parameter types are part of the lookup signature. This is especially important with overloading: a method name alone is not enough to select one overload unambiguously.
getDeclaredField() or getDeclaredMethod()
can locate a non-public member, but that does not automatically mean the code may read or invoke it.