Experienced Java Interview Questions

What is reflection in Java?

Reflection (the package java.lang.reflect) lets code look at classes, methods and fields at run time, and call them, even if the names were not known when the code was written.

import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {
    public static class Greeter {
        public String hello(String name) { return "Hello, " + name; }
        public int twice(int n) { return n * 2; }
    }

    public static void main(String[] args) throws Exception {
        Class<?> c = Class.forName("Main$Greeter");
        System.out.println(c.getSimpleName());

        Object obj = c.getDeclaredConstructor().newInstance();
        Method hello = c.getMethod("hello", String.class);
        System.out.println(hello.invoke(obj, "Riya"));

        String[] names = Arrays.stream(c.getDeclaredMethods()).map(Method::getName).sorted().toArray(String[]::new);
        System.out.println(Arrays.toString(names));
    }
}
Output

Greeter
Hello, Riya
[hello, twice]

  • It is powerful but slower, and it breaks the safety checks of the compiler. Use it for frameworks and tools, not for normal code.
  • Modern Java also limits reflection on the internals of the JDK (modules).