0Pricing
Java Academy · Lesson

Invoking Methods and Accessing Fields

Call private methods and set inaccessible fields using Method.invoke and Field.set with setAccessible.

Invoking Methods and Accessing Fields is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

setAccessible: Bypassing Visibility

Call field.setAccessible(true) or method.setAccessible(true) to bypass Java's access control. Required for private members. Requires appropriate module access in Java 9+.

Field f = User.class.getDeclaredField("name");
f.setAccessible(true);
User u = new User("Alice", 30);
System.out.println(f.get(u));  // "Alice"
f.set(u, "Bob");               // mutate the private field
System.out.println(u.getName()); // "Bob"

Reading Field Values

Use field.get(instance) to read any field value (boxed for primitives). For static fields, pass null as the instance.

Field f = MyClass.class.getDeclaredField("count");
f.setAccessible(true);
int count = (int) f.get(null); // static field → null instance

Setting Field Values

Use field.set(instance, value) to write a field. The value type must match or be auto-unboxed. Setting a final field via reflection is undefined behavior in modern JVMs.

Field nameField = User.class.getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(user, "Charlie");

Invoking Methods via Reflection

Retrieve a Method object, call setAccessible(true), then invoke it with method.invoke(instance, args...). The return value is Object.

Method greet = User.class.getDeclaredMethod("greet", String.class);
greet.setAccessible(true);
String result = (String) greet.invoke(user, "World");
System.out.println(result);

Handling InvocationTargetException

If the invoked method throws an exception, reflection wraps it in InvocationTargetException. Unwrap it with getCause().

try {
    method.invoke(obj, args);
} catch (InvocationTargetException e) {
    Throwable cause = e.getCause();
    System.err.println("Method threw: " + cause.getMessage());
} catch (IllegalAccessException | NoSuchMethodException e) {
    System.err.println("Reflection error: " + e.getMessage());
}

Invoking Static Methods

Pass null as the instance argument when invoking static methods.

Method parseInt = Integer.class.getDeclaredMethod("parseInt", String.class);
int value = (int) parseInt.invoke(null, "42"); // null = static
System.out.println(value); // 42

Creating Instances via Constructor

Get a Constructor, call setAccessible(true) for private ones, then newInstance(args...).

Constructor<User> ctor = User.class.getDeclaredConstructor(String.class, int.class);
ctor.setAccessible(true);
User u = ctor.newInstance("Diana", 28);
System.out.println(u);

Reflection in Frameworks: Spring DI

Spring uses reflection to instantiate beans and inject dependencies. It calls private constructors and sets private fields to wire the application context.

Module Access in Java 9+

In Java 9+, modules restrict setAccessible by default. If the class is in a named module, you may need to open the package: --add-opens java.base/java.lang=ALL-UNNAMED.

// JVM flag to open a package for reflection:
// --add-opens java.base/java.lang=ALL-UNNAMED

MethodHandles as a Faster Alternative

MethodHandles.lookup().findVirtual() provides reflective method invocation with near-direct-call performance after JIT optimization. Preferred in performance-critical library code.

MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(User.class, MethodHandles.lookup());
MethodHandle handle = lookup.findVirtual(User.class, "getName", MethodType.methodType(String.class));
String name = (String) handle.invoke(user);

Reflection Best Practices

Cache Field/Method objects — never retrieve them in hot loops. Wrap reflection in service classes. Consider MethodHandles for performance. Prefer interfaces over reflection when possible.

Quick Check

When a reflected method throws, what exception wraps the cause?

Recap

Use setAccessible(true) to access private members. Invoke methods via method.invoke(). Unwrap InvocationTargetException. Cache reflective objects. Prefer MethodHandles for hot paths.

Frequently asked questions

Is the “Invoking Methods and Accessing Fields” lesson free?

Yes — the full text of “Invoking Methods and Accessing Fields” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Invoking Methods and Accessing Fields”?

Call private methods and set inaccessible fields using Method.invoke and Field.set with setAccessible. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Invoking Methods and Accessing Fields” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Class Inspection with Reflection
  2. Invoking Methods and Accessing Fields
  3. Dynamic Proxies with InvocationHandler
  4. Reflection Performance and Alternatives
← Back to Java Academy