简体   繁体   English

如何通过Java编码在运行时将My Jar加载到ClassPath?

[英]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.

相关问题 Java反思:如何在不将另一个项目或JAR添加到我的类路径的情况下从另一个项目加载一个类? - Java reflection: How can I load a class from another project without adding that project or JAR to my classpath? 在运行时从外部jar,classpath加载图像 - Load image from external jar ,classpath at runtime 在 java 9 下在运行时将 jar 添加到类路径 - Add jar to classpath at runtime under java 9 Java如何使用System ClassLoader(无URLClassLoader)从类路径中的jar中加载类? - Java How to load classes out of a jar in the classpath with the System ClassLoader (no URLClassLoader)? 在运行时在类路径上加载java.io.File - Load java.io.File At Runtime On Classpath 如何在 jar 中加载类路径 @PropertySource? - How to load classpath @PropertySource inside a jar? 运行时执行 (JAR) 找不到 Java CLASSPATH 和连接器 J - Runtime execution (JAR) cannot locate Java CLASSPATH and Connector J 如何在运行时将新的Java文件加载到现有的Jar中? - How to load a new java file into existing Jar during runtime? 如何在运行时使用 Java 调试接口从 Jar 文件加载 class - How to load a class from a Jar file at runtime with the Java Debug Interface 如何在Heroku Java部署中的类路径中添加jar? - How to add a jar in classpath in Heroku Java deployment?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM