简体   繁体   中英

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

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> . 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

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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