dimanche 5 août 2018

Is it possible to cast an object to the object that has exactly the same structure as its abstract parrent (,not its parrent) in all java versions?

I have a java library named testlib.jar and it has a abstract class as below:

com.test;
public abstract class AbstractClass {
    public abstract void foo();
}

and a class named MyClass as below:

com.test;
public class MyClass extends AbstractClass{
    @Override
    public void foo() {
        System.out.println("foo is called in MyClass");
    }
}

that's it. In my application I have a abstract class as below:

com.test;
public abstract class AbstractClass {
    public abstract void foo();
}

So it's the same as the abstract class in testlib.jar. Here I loaded the testlib.jar file and instantiated an object of MyClass and casted it to the abstract class that is known to my application (the second one):

URLClassLoader urlClassLoader = new URLClassLoader(
            new URL[]{new URL("file:\\path\\to\\testlib.jar")});
Class<AbstractClass> MyClass = (Class<AbstractClass>)urlClassLoader.loadClass("com.test.MyClass");
Constructor<AbstractClass> c = MyClass.getConstructor();
AbstractClass myObject = c.newInstance();
myObject.foo();

Output:

foo is called in MyClass

Note that I'm casting MyClass to a class that is not really its parent.

Know here I've two questions:

1- Does this approach work in all JVMs?

2- How does JVM handle this cast operation internally?





Aucun commentaire:

Enregistrer un commentaire