Command Palette

Search for a command to run...

Back to the lesson: Topic 15.2 — Reflection
Core Java · Example 1 of 4 Java 8+

Inspecting a class: fields, methods, constructors

getGenericType still knows List<String>: generic signatures of declarations survive erasure, only objects lose their type arguments.

Reflection (java.lang.reflect) lets a running program examine classes it was never compiled against: list their fields, methods and constructors, create objects, call methods and read fields by name. It powers frameworks, serializers and test runners, at the cost of speed, compile-time safety and encapsulation, and since Java 16 the module system blocks it from reaching into JDK internals.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write toMap(Object o) that returns a TreeMap of every declared field name to its value, using reflection, and print it for an object with three private fields.

02

Call a static method Math.max(int, int) through reflection and print the result.

03

Write a method that copies every non-static field from one object to another of the same class, and show it working.

Explain it without notes

01

What is reflection, and where is it used in real systems?

02

What is the difference between getMethods() and getDeclaredMethods()?

03

Why does a reflective call throw InvocationTargetException, and how do you handle it?

04

How did the module system change what setAccessible(true) can do?

05

What are the costs of reflection, and what are the alternatives?

Inspecting a class: fields, methods, constructors Java 8+
Sign in to run this example in your browser.

Expected output

class Product extends Object implements Priced
field: public static final java.lang.String CURRENCY
field: private final java.lang.String name
field: private long price
field: protected java.util.List<java.lang.String> tags
method: private void applyDiscount(int)
method: public String getName()
method: public long price()
constructor: public Product()
constructor: public Product(String, long)