简体   繁体   English

java .cast方法的不同行为

[英]Different behavior of java .cast method

I have this piece of code (Child is just an empty child of Object) and I do not understand why the last call does not give the same result as the second 我有这段代码(Child只是Object的空子)我不明白为什么最后一次调用没有给出与第二次调用相同的结果

Thanks for help 感谢帮助

public class App {
  void process(Object o) {
    System.out.println("I have processed an object");
  }

  void process(Child c) {
    System.out.println("I have processed a child");
  }

  public static void main (String[] args) {
    Object o = new Child();

    Class<?> cl = Child.class;  

    App app = new App();
    app.process(o);
    app.process(Child.class.cast(o));
    app.process(cl.cast(o));
  }
}   

The output is 输出是

I have processed an object
I have processed a child
I have processed an object

Most probably because the static type of cl is Class<?> (which is effectively Class<Object> ), while that of Child.class is Class<Child> . 很可能是因为cl的静态类型是Class<?> (实际上是Class<Object> ),而Child.class的静态类型是Class<Child> The compiler chooses the method to call based solely on the static type it sees, not on the actual type of the object. 编译器选择仅基于它看到的静态类型调用的方法,而不是基于对象的实际类型。

So declaring your variable as 所以声明你的变量为

Class<Child> cl = Child.class;

should give you the result you expected. 应该给你你想要的结果。

You should use Java reflection to do this 您应该使用Java反射来执行此操作

public static void main(String[] args) {
    Object o = new Child();
    App app = new App();

    try {
        Method m = App.class.getMethod("process", o.getClass());
        m.invoke(app, o);

    } catch (Exception e) {
        e.printStackTrace();
    }
}: 

Although you have an Object container, the output is now : I have processed a child 虽然你有一个Object容器,但输出现在是: 我已经处理了一个子容器

public T cast(Object obj) {
if (obj != null && !isInstance(obj))
    throw new ClassCastException();
return (T) obj;
}

when writtern by this: 当写作时:

Class<?> cl = Child.class;  

T is repalced by Object, so return (Object)obj; T由Object重新定义,因此返回(Object)obj;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM