Java Reference ยท Language Features by Version
Reflection: Method, Field and Constructor
Reference for java.lang.reflect.Method, Field and Constructor: look members up, call methods, read and write fields, create objects, handle exceptions.
Once you have a Class object (Reflection), three types represent its members: Field for variables, Method for methods and Constructor<T> for constructors. Each can be looked up by name and parameter types, inspected (modifiers, types, annotations) and used: Field.get/set, Method.invoke, Constructor.newInstance.
All three extend AccessibleObject, whose setAccessible(true) lets reflective code reach private members of classes in the same module (or in packages that are opens-ed to you). That power is why frameworks can fill private fields, and also why reflection should be limited to infrastructure code.
Method m = String.class.getMethod("substring", int.class, int.class); Object result = m.invoke("reflection", 0, 4); // "refl" Field f = Point.class.getDeclaredField("x"); f.setAccessible(true); f.setInt(point, 10);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
What each class gives you
Method
| Member | Description |
|---|---|
invoke(Object target, Object... args) |
Calls the method. Static methods ignore target (pass null). Primitives are boxed and unboxed. Returns null for void. |
getName(), getReturnType(), getParameterTypes(), getParameterCount(), getParameters() |
Signature details. Parameter.getName() gives real names only if compiled with -parameters. |
getGenericReturnType(), getGenericParameterTypes() |
Types including generics. |
getExceptionTypes(), getModifiers(), isDefault(), isVarArgs(), isSynthetic() |
Other metadata. |
Field
| Member | Description |
|---|---|
get(Object), set(Object, Object) |
Read and write. Primitive shortcuts: getInt, setInt, getBoolean, ... Static fields ignore the target. |
getType(), getGenericType(), getName(), getModifiers() |
Declaration details. |
Constructor<T>
| Member | Description |
|---|---|
newInstance(Object... args) |
Creates an object; Class.newInstance() is deprecated, use getDeclaredConstructor().newInstance(). |
getParameterTypes(), getModifiers(), isVarArgs() |
Metadata. |
Looking things up
| Call | Finds |
|---|---|
getMethod(name, types...) |
A public method, including inherited ones. |
getDeclaredMethod(name, types...) |
Any method declared in this class, not inherited ones. |
getField(name) / getDeclaredField(name) |
Same split for fields. |
getConstructor(types...) / getDeclaredConstructor(types...) |
Public constructor / any constructor of this class. |
Usage notes
- Exceptions thrown by the invoked method come wrapped in
InvocationTargetException; callgetCause()to get the real one. Misuse (wrong arguments) throwsIllegalArgumentException; a missingsetAccessiblethrowsIllegalAccessException;setAccessiblecan throwInaccessibleObjectExceptionwhen a module forbids it. - Parameter types must match exactly in a lookup:
getMethod("deposit", Integer.class)does not finddeposit(int). Useint.class. - Final fields:
seton a final field throwsIllegalAccessException. For a final instance field of an ordinary class,setAccessible(true)has historically lifted that, but the JDK is restricting it (records and hidden classes already refuse) and optimizers may keep using the old value. Never rely on it.static finalfields cannot be changed. - Reflection hides compile-time errors: renaming a method breaks string lookups at run time. Keep reflective code in one place with tests.
- Calls are slower than direct ones and cannot be inlined as easily; cache
MethodandFieldobjects.MethodHandle(java.lang.invoke) is faster and more flexible when you need many calls. getDeclaredMethods()also returns compiler-generated methods (bridge and synthetic methods, lambda bodies likelambda$main$0).