简体   繁体   中英

How to cast an Object when we only have the .class files?

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.

To use a Java class, you do not need the source file. You only need the compiled class file, and you need to make sure that the Java compiler can find the class file at the right place.

Make sure that the directory that contains the file ObjectFoo.class is in the classpath when you compile and run your own code. You can do that by using the -cp option of the javac and java commands:

javac -cp C:\SomeDirectory;. MyProgram.java
java -cp C:\SomeDirectory;. MyProgram.java

where C:\\SomeDirectory is the directory that contains ObjectFoo.class .

Note: There is also no reason to use reflection, with Class.forName(...) etc. to create a new instance of ObjectFoo . Just use the new operator instead; then you also don't need to cast.

ObjectFoo object = new ObjectFoo();

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