Skip to content
gqlxj1987's Blog
Go back

PWS动态算子加载

Edit page
@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部分

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);

	}

}

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


Edit page
Share this post on:

Previous Post
楚门的世界
Next Post
Git Flight Rules