DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

PWS动态算子加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Slf4j
public class URLClassLoaderTest {
private static final String remoteJarPath = "http://localhost:8080/operators/base-operator.jar";
@Test
public void testLoadRemoteJar() throws Exception {
URI uri = new URI(remoteJarPath);
URLClassLoader classLoader = new URLClassLoader(new URL[]{uri.toURL()});
Thread.currentThread().setContextClassLoader(classLoader);
ServiceLoader<Operator> loader = ServiceLoader.load(Operator.class);
Iterator<Operator> iterator = loader.iterator();
while (iterator.hasNext()) {
try {
Operator operator = iterator.next();
log.info("OperatorInfo: name={}, platform={}", operator.getName(), operator.getPlatform());
} catch (Exception e) {
log.warn("Failed to instantiate operator", e);
}
}
}
}

以代码为例说明:

  • 采用URLClassLoader的方式来加载jar包
  • 在此基础上,加入SerivceLoader来加载类Operator的class

关于URLClassLoader部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.jcg;

/**
* @author ashraf
*
*/
public class Bean {

public void sayHello() {
System.out.println("Hello from loaded Bean class !!!");
}

}




package com.jcg;

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

/**
* @author ashraf
*
*/
public class URLClassLoaderTest {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {

// Getting the jar URL which contains target class
URL[] classLoaderUrls = new URL[]{new URL("file:///home/ashraf/Desktop/simple-bean-1.0.jar")};

// Create a new URLClassLoader
URLClassLoader urlClassLoader = new URLClassLoader(classLoaderUrls);

// Load the target class
Class<?> beanClass = urlClassLoader.loadClass("com.jcg.Bean");

// Create a new instance from the loaded class
Constructor<?> constructor = beanClass.getConstructor();
Object beanObj = constructor.newInstance();

// Getting a method from the loaded class and invoke it
Method method = beanClass.getMethod("sayHello");
method.invoke(beanObj);

}

}

见上面的例子,利用反射的方式?