java—运行时反射

0tdrvxhp  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(401)

考虑以下代码

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 {
    }
}

我期望输出为“class a”,但得到“class a$b”。
有没有办法将对象x转换为.class,这样在方法调用中使用时,运行时会认为x是.class?

yptwkmov

yptwkmov1#

不,强制转换不会改变对象的类型,它只会改变引用的类型。
例如,此代码:

B b = new B();
A a = (A) b;
a.doSomething();

不需要 b 强行使之成为 A ,然后呼叫 doSomething() 类中的方法。强制转换只允许引用类型的对象 B 好像是那种类型的 A .
不能更改对象的运行时类型。

gdx19jrr

gdx19jrr2#

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

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

如果你想要一个实际上只是 A ,您需要创建 A 相反。例如,您可能有:

public A(B other) {
    // Copy fields from "other" into the new object
}

相关问题