java - 在运行时通过反射进行强制转换

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

我期望输出“A类”,但我得到“A$B类”

有没有办法将对象 x 强制转换为 A.class,以便在方法调用中使用时,运行时会认为 x 属于 A.class?

最佳答案

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

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
}

关于java - 在运行时通过反射进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1668558/

相关文章:

go - 如何将包含错误对象的 reflect.Value 分配给错误类型的普通变量?

arrays - 在 MATLAB R2018a 及更新版本中无需数据复制即可将复数转换为实数

java - Java 中的泛型类推断

c# - "On Demand"动态实例化类的依赖注入(inject)

java - 如何通过 Java 17 中的反射获取所有 Record 字段及其值?

c# - 与 C++ 的 dynamic_cast 等效的 C# 是什么?

java - "Invalid signature file digest"通过Maven添加Janino包出错

java - 读取文件 - 哪种方法是可测试的?

java - 函数式编程应用

java - 我想在jaxb的派生类中隐藏一个字段