[英]How to load My Jar to ClassPath at runtime through Java Coding?
I am working with Swing in Net Beans. 我正在使用Net Beans中的Swing。 I have my own jar which contains classes and methods inside it.
我有自己的jar,其中包含类和方法。 I will call those classes and methods using JAVA Reflection API but before that I want to load my Jar into class path at run time.
我将使用JAVA Reflection API调用这些类和方法,但在此之前,我想在运行时将Jar加载到类路径中。 I have a J Button and on click of that I am getting Jar Name and Jar path.
我有一个J按钮,单击它,我得到了Jar名称和Jar路径。 But I am failing to load Jar to classpath at run time.
但是我无法在运行时将Jar加载到类路径中。 Got some links but were not helpful.
有一些链接,但没有帮助。 Please provide me with simple example.
请给我提供一个简单的例子。 I should load my jar to classpath.
我应该将jar加载到classpath。 That's the only problem for me.I will take care of that.
这是我唯一的问题。我会解决的。 Please help.
请帮忙。
You can load classes at run time through the use of a ClassLoader
, take a look at URLClassLoader
for example 您可以通过使用
ClassLoader
在运行时ClassLoader
,例如以URLClassLoader
为例
File yourJarFile = ...;
URLClassLoader classLoader = new URLClassLoader(new URL[]{yourJarFile.toURI().toURL()});
This will then allow you to load classes and instantiate them... 然后,这将允许您加载类并实例化它们。
Class class = classLoader.loadClass("fully.qualified.packagename.to.your.AwesomeClass");
You can then instantiate them using something like... 然后,您可以使用类似...的方法实例化它们。
Object obj = class.newInstance();
Or reflection if you want to use a specific constructor. 如果您要使用特定的构造函数,请执行反射操作。 Just remember, you won't be able to reference these classes directly within the current class loader context, as the current class loader knows nothing about them
请记住,您将无法直接在当前类加载器上下文中引用这些类,因为当前类加载器对此一无所知
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.