在运行时使用反射进行转换

Pet*_*Mmm 0 java reflection casting

考虑以下代码

   public class A {

    public static void main(String[] args) {
        new A().main();
    }

    void main() {

        B b = new B();
        Object x = getClass().cast(b);

        test(x);
    }

    void test(Object x) {
        System.err.println(x.getClass());
    }

    class B extends A {
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望输出"A级",但我得到"A级B级".

有没有办法将对象x转换为A.class,所以当在方法调用中使用时,运行时会认为x是A.class?

Jon*_*eet 6

强制转换不会更改对象的实际类型.例如:

String x = "hello";
Object o = (Object) x; // Cast isn't actually required
System.out.println(o.getClass()); // Prints java.lang.String
Run Code Online (Sandbox Code Playgroud)

如果你想要一个实际上只是一个实例的对象A,你需要创建一个实例A.例如,您可能有:

public A(B other) {
    // Copy fields from "other" into the new object
}
Run Code Online (Sandbox Code Playgroud)