Java 反射

Class 对象的获取、动态创建实例、调用方法与访问字段。

Advanced
Key Points反射在运行时检查并操作类;能突破 private(需 setAccessible),但慢且不安全,框架大量使用、业务代码少用。

获取 Class 对象

Three routes: Type.class (known at compile time, safest), obj.getClass(), and Class.forName("fqcn") for configuration-driven loading — the last may throw ClassNotFoundException.

Java
public class GetClass {
    public static void main(String[] args) throws Exception {
        Class<?> a = String.class;
        Class<?> b = "x".getClass();
        Class<?> c = Class.forName("java.lang.String");

        System.out.println(a == b);
        System.out.println(b == c);
        System.out.println(a.getSimpleName());
        System.out.println(a.getPackageName());
    }
}
Output
true
true
String
java.lang

创建实例与调用方法

getDeclaredConstructor().newInstance() constructs an object; getMethod finds public methods, getDeclaredMethod any declared in the class (private included), and invoke runs them.

Java
import java.lang.reflect.Method;

public class InvokeDemo {
    public static void main(String[] args) throws Exception {
        Class<?> c = Class.forName("java.lang.String");

        Object s = c.getConstructor(String.class).newInstance("hello");
        Method m = c.getMethod("toUpperCase");

        System.out.println(s);
        System.out.println(m.invoke(s));
        System.out.println(m.getReturnType().getSimpleName());
    }
}
Output
hello
HELLO
String

访问私有成员

getDeclaredField reaches private fields, but you must call setAccessible(true) first. Since Java 17 strong encapsulation blocks this unless the module opens up.

Java
import java.lang.reflect.Field;

class Secret {
    private String value = "hidden";
}

public class PrivateAccess {
    public static void main(String[] args) throws Exception {
        Secret s = new Secret();
        Field f = Secret.class.getDeclaredField("value");
        f.setAccessible(true);

        System.out.println(f.get(s));
        f.set(s, "changed");
        System.out.println(f.get(s));
    }
}
Output
hidden
changed
Reflection defeats compile-time checking, costs performance and may trip security restrictions. Prefer interfaces and polymorphism in business code; reserve reflection for frameworks, serializers and test tooling.

Friends & Partners