考虑以下代码
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/