如何在运行时通过Java编码将My Jar加载到ClassPath? [英] How to load My Jar to ClassPath at runtime through Java Coding?

查看:69
本文介绍了如何在运行时通过Java编码将My Jar加载到ClassPath?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Net Beans中的Swing.我有自己的jar,其中包含类和方法.我将使用JAVA Reflection API调用这些类和方法,但在此之前,我想在运行时将Jar加载到类路径中.我有一个J按钮,单击它,我得到了Jar名称和Jar路径.但是我无法在运行时将Jar加载到类路径中.有一些链接,但没有帮助.请给我提供一个简单的例子.我应该将jar加载到classpath.那是我唯一的问题.我会解决的.请帮忙.

I am working with Swing in Net Beans. I have my own jar which contains classes and methods inside it. 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. I have a J Button and on click of that I am getting Jar Name and Jar path. But I am failing to load Jar to classpath at run time. Got some links but were not helpful. Please provide me with simple example. I should load my jar to classpath. That's the only problem for me.I will take care of that. Please help.

推荐答案

您可以在运行时通过使用ClassLoader加载类,请查看

You can load classes at run time through the use of a ClassLoader, take a look at URLClassLoader for example

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

这篇关于如何在运行时通过Java编码将My Jar加载到ClassPath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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