Let’s say I have a class file named ObjectFoo.class but I don’t have access to ObjectFoo.java source file, since the class file is created during runtime. Is there a way to cast an object in this case ?
At the moment, I’m using this code to cast the object, but in this example I need to have ObjectFoo.java in my classpath :
Class c = Class.forName("ObjectFoo");
ObjectFoo object = (ObjectFoo) c.newInstance();
The goal is to instantiate an object from its class file using Java reflection.
I’m looking for a solution using only Java API and no other third-party libraries.
Thanks in advance for your answer !
Jonathan.
When you use third-party libraries, packages as .jar files, you will always compile and run against .class files. The .jar archives contain .class files, not .java ones.
So, the code above is correct, if the ObjectFoo class doesn’t belong to a package. Otherwise, you will have to put the full package like path to the class.