您的位置:首页 > 编程语言 > Java开发

JAVA加载JAR包并调用JAR包中某个类的某个方法

2017-08-17 10:09 337 查看
JAVA加载JAR包并调用JAR包中某个类的某个方法示例如下:

package com.example;

public class Runner implements Runnable{

public void run() {
System.out.println("the writer is running...");
}

}


需要将以上类打包成JAR,通过URLClassLoader读取

import org.junit.Test;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
* Main
* Created by Joker on 2017/8/16.
*/
public class Main {
@Test
public void test() throws Exception {

URL url = new URL("file:E:/JavaJars/OtherJar/runner.jar");
URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
Class<?> clazz = urlClassLoader.loadClass("com.example.Runner");
//Runnable runnable = (Runnable) clazz.newInstance();
//runnable.run();
Method method = clazz.getMethod("run");
method.invoke(clazz.newInstance());

}
}


通常情况下:当某个项目需要较高的扩展性时,我们会采用这种方法,一般会将项目需要灵活扩展的地方抽象出对应的接口,在写外部JAR时引入并逐一实现事前约定的好的接口。这样当系统运行时,按照配置文件载入JAR包并读取Class时,可以强转成对应接口以满足我们的需求。当然也可以通过method的invoke调用,但这种方式并不提倡。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: