classloader就是java的加载器。如何正确使用
自己打包一个自定义的jar包
package com.py.classloader.test.clazz;
public class TestBean {
String str;
public TestBean(String str) {
this.str = str;
}
@Override
public String toString() {
return "test bean:" + str;
}
}
package com.py.classloader.test.clazz;
import com.py.classloader.test.Test1S;
public class TestService {
public static TestBean getTestBean(String str) {
System.out.println(Test1S.test());
TestBean t = new TestBean(str);
return t;
}
}
package com.py.classloader.test.clazz;
/**
* 测试主线程
*
* @author cyd
* @date 2018年5月16日
*/
public class Main implements Runnable {
@Override
public void run() {
new Thread(()->{
System.out.println("main start");
int i = 0;
while (true) {
System.out.println(TestService.getTestBean("test" + ++i));
try {
Thread.sleep(2000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project default="create_test_jar" name="Create Runnable Jar for Project GameRun with libraries in sub-folder">
<!--this file was created by Eclipse Runnable JAR Export Wizard-->
<!--ANT 1.7 is required -->
<!--define folder properties-->
<property name="dir.buildfile" value="."/>
<property name="dir.jarfile" value="${dir.buildfile}/target"/>
<target name="create_test_jar">
<jar destfile="${dir.jarfile}/test.jar">
<manifest>
</manifest>
<fileset dir="${dir.buildfile}/bin"/>
</jar>
</target>
</project>
打包完成后把test.jar放到测试main函数所在工程目录下
package com.py.classloader.test;
public class Test1S {
public static String test() {
return "Test1S.test()+564564";
}
}
package com.py.classloader.test;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
/**
* 类加载器ClassLoader测试
*
* @author cyd
* @date 2018年5月16日
*/
public class ClassLoaderTestMain {
static File jarFile = new File("jar_classloader/test.jar");
public static void main(String[] args) {
try {
testMainRun();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static ClassLoader getClassLoader() throws Exception {
ClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, ClassLoaderTestMain.class.getClassLoader());
return loader;
}
public static void testMainRun() throws Exception {
try {
Class<?> mainLoaderClazz = ClassLoaderTestMain.class.getClassLoader().loadClass("com.py.classloader.test.clazz.Main");
System.out.println(mainLoaderClazz);
} catch (Exception e) {
e.printStackTrace();
}
ClassLoader loader = getClassLoader();
Class<?> clazz = loader.loadClass("com.py.classloader.test.clazz.Main");
Runnable main = (Runnable)clazz.newInstance();
main.run();
}
}
就可以得到运行结果
可见这个test.jar中的类在主加载器中是加载不到的。
这样就把纯业务逻辑分离出来打成独立的jar包,然后通过通过ClassLoader配合文件监听系统 比如apache的commons-vfs来做java的热部署