Java-从jar文件创建类 [英] Java - Create a Class from a Jar File

查看:122
本文介绍了Java-从jar文件创建类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从jar文件中加载类,然后从中创建对象?

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

注意:编译程序时jar文件不存在,但稍后由用户添加,并在用户启动程序时加载.

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.

我的代码是这样的:用户有一个jar文件,里面只有一个已编译的Java类.然后,用户将这个jar文件放在一个目录中,并启动我的程序,该程序通过目录进行查找并找到这个jar文件.然后,它将加载此jar文件并从中创建一个类,然后从该类中创建一个对象并将其添加到数组中.

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.

除了从jar文件(作为java.io文件加载)创建一个类,然后从该类创建和对象之外,我一无所有.

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.

有帮助吗?谢谢.

推荐答案

您正在寻找

You're looking for Class#forNameand 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();

针对这些情况的一个很好的例子是使用JDBC(正如链接也指出的那样),因为您初始化了要连接的db引擎驱动程序的对象.请记住,该驱动程序不是从导入的jar到您的项目中,它可能是MySQL,Oracle或MSSQL Server的jar,您只需提供驱动程序类名,然后让JDBC API和jar处理SQL工作即可.

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");

此外,对于此动态加载jar的特定问题,还有一些问题和答案:

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

这篇关于Java-从jar文件创建类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆