Java - creating 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 does not exist when the program is compiled, but is added by the user later and loaded when the user starts the program.

I like my code: the user has a jar file in which there is not only a compiled java class. Then, the user places this jar file in a directory and runs my program, which scans the directory and finds this jar file. Then it loads this jar file and creates a class from it, which then creates an object from it and adds it to the array.

I have everything except creating a class from a jar file (loaded as a java.io file), and then creating and an object from this class.

Any help? Thank.

+5
source share
2 answers

You are looking for Class#forNameand Class#newInstance.

This link serves as a good example of class initialization, 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 to use JDBC (as the link indicates), because you are initializing the db engine driver object that you want to connect. Remember that this driver comes from the imported bank into your project, it can be a bank for MySQL, Oracle or MSSQL Server, you just provide the driver class name and allow the JDBC API and the bank to process SQL work.

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

In addition, for this specific task, when loading a jar, questions and answers dynamically arise:

+4
source

? jar .
, , jvm

: @Luiggi ,

0

All Articles