JAVA 动态加载类 并运行

lindeqiang 2007-07-13 12:21:24
比如我有一个jar文件,里面有一个A类,
jar文件放在c:\下面

我在一个JAVA工程的B类中,要加载这个jar文件,并获取A类的实例和执行A的test()方法,该怎么实现,谢谢各位~
(前提不将这个jar包放在classpath)
...全文
2032 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangcaibin 2007-07-14
  • 打赏
  • 举报
回复
利用反射API
joejoe1991 2007-07-14
  • 打赏
  • 举报
回复
XXXX.getClass().newInstance();
lalakid 2007-07-14
  • 打赏
  • 举报
回复
留名
Inhibitory 2007-07-14
  • 打赏
  • 举报
回复
java.lang.Class.newInstance()
lindeqiang 2007-07-14
  • 打赏
  • 举报
回复
现在我加载这个jar是没有问题了,也能读取某个class的方法或属性,但是
我现在怎么实现创建一个实例来运行这个class中的某个方法呢?
或者说是,怎么获取这个class实例的引用呢?
slaser 2007-07-13
  • 打赏
  • 举报
回复
用classloader阿。
guyong009 2007-07-13
  • 打赏
  • 举报
回复
up
真的很小奚 2007-07-13
  • 打赏
  • 举报
回复
期待LZ早日解决 不用classpath
lindeqiang 2007-07-13
  • 打赏
  • 举报
回复
我想做一个插件的框架,就像eclipse,有一个plug-in文件夹,我想直接根据相应的描述(jar的一个主类),直接在框架中直接动态载入此类
Inhibitory 2007-07-13
  • 打赏
  • 举报
回复
请问,你为什么要这样做?
lcllcl987 2007-07-13
  • 打赏
  • 举报
回复
手头有一断代码,不知能否帮你:
public static StringBuffer readPackageResource(String packageResource)
{
if (packageResource == null)
return null;
try
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream(packageResource);
if (is == null)
{
loader = FileUtil.class.getClassLoader();
is = loader.getResourceAsStream(packageResource);
}
BufferedReader bf = new BufferedReader(new InputStreamReader(is));
StringBuffer recordBuf = new StringBuffer();
String record = null;
while ((record = bf.readLine()) != null)
{
recordBuf.append(record + "\n");
}
bf.close();
is.close();
return recordBuf;
}
catch (Exception ex)
{
CommonLog.debug("readPackageResource(): " + ex.toString());
ex.printStackTrace();
}
return null;
}
grp0606grp 2007-07-13
  • 打赏
  • 举报
回复
up
weihthchk 2007-07-13
  • 打赏
  • 举报
回复
java.net包中有一个URLClassLoader,可以载入.jar文件中的类。
Inhibitory 2007-07-13
  • 打赏
  • 举报
回复
那用Class.forName()试试,这个可以返回一个类的实例,如数据库的时候就是用这个动态取得Driver的,好像还要用到反射机制。
public static Class<?> forName(String className)
throws ClassNotFoundException
Returns the Class object associated with the class or interface with the given string name. Invoking this method is equivalent to:
Class.forName(className, true, currentLoader)

where currentLoader denotes the defining class loader of the current class.
For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:

Class t = Class.forName("java.lang.Thread")

A call to forName("X") causes the class named X to be initialized.


Parameters:
className - the fully qualified name of the desired class.
Returns:
the Class object for the class with the specified name.
Throws:
LinkageError - if the linkage fails
ExceptionInInitializerError - if the initialization provoked by this method fails
ClassNotFoundException - if the class cannot be located
myydzhz 2007-07-13
  • 打赏
  • 举报
回复
同意用classloader

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧