开发者

Cast down with reflection at runtime

Considering following code

   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());
    }

    clas开发者_如何学编程s B extends A {
    }
}

I expected as output "class A" but i get "class A$B".

Is there a way to cast down the object x to A.class so when using in a method call the runtime will think x is of A.class ?


A cast doesn't change the actual type of the object. For example:

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

If you want an object which is actually just an instance of A, you need to create an instance of A instead. For instance, you might have:

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


No. Casting doesn't change the type of an object, it just changes what type you have a reference to.

For example, this code:

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

Doesn't take b and forcibly make it into an instance of A, and then call the doSomething() method in class A. All the casting does is allow you to reference the object of type B as if it were of type A.

You cannot change the runtime type of an object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜