简体   繁体   中英

Instantiate a class outside of jar file in java?

Is it possible to load a class outside the jar file.

  • Janibot // Main Directory
    • lib // sub directory
      • Robot.java
      • Robot.class
    • Janibot.jar // sub directory

above is the structure of directory. I want to do is to instantiate a Robot class when I run the Janibot.jar using Class.forName but it always return a classnotfoundexception.

my plan is to edit the Robot.java in a JtextArea and compile it at runtime and then instantiate a Robot.class

Yes, as long as you are using standard Java*, then where a class is deployed (jar file, loose class) does not matter. What does matter is that you launch your application with all relevant class directories and jar files on the class path.

Assuming you are in the root directory of the project (Janibot), the following java command will accomplish this:

java -classpath ./lib:./janibot.jar  <class_to_execute>

(* OSGI would be an exception to this. OSGI uses a different class loader with a different set of rules, but I assume that is is not in the picture here)

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