简体   繁体   中英

Java - Create a Class from a Jar File

Is it possible to load a class from a jar file and then create an object from it?

Note: The jar file is not there when the program is compiled, but is added by the user later and is loaded in when the user starts the program.

My code goes likes this: The user has a jar file with nothing but a compiled java class in it. The user then puts this jar file in a directory and starts my program which looks through the directory and finds this jar file. It then loads this jar file and creates a class from it which it then creates an object from that and adds it to an array.

I have everything down except for creating a class from the jar file (loaded as a java.io File) and then creating and object from that class.

Any help? Thanks.

You're looking for Class#forName and Class#newInstance methods.

This link provides a good example about initializing a class knowing its name (extracted from the link):

Class c = Class.forName("com.xyzws.AClass");
AClass a = (AClass)c.newInstance();

A good example for these situations is using JDBC (as the link also points out), because you initialize an object of the db engine driver you want to connect. Remember than this driver comes from an imported jar into your project, it could be a jar to MySQL, Oracle or MSSQL Server, you just provide the driver class name and let the JDBC API and the jar handles the SQL work.

Class.forName("org.gjt.mm.mysql.Driver");
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");

Also, for this specific problem loading the jar dynamically, there are question and answer:

A simpler? way would be for the user to put the jar file in the classpath.
That way your code will have access to the class that will be loaded by the jvm

Edit: Even @Luiggi's answer assumes that the jar is in the classpath

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