package com.yang.myclass.hotswap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class MyClassLoader3 extends ClassLoader {
/**
* 自定义类加载器
* @param name
* @return
* @throws ClassNotFoundException
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classByte = getClassData(name);
if(classByte==null){
throw new ClassNotFoundException();
}else{
//生成class
return defineClass(name,classByte,0,classByte.length);
}
}
private byte[] getClassData(String className){
//读取类文件的路径
String classPath = "/" + className.replace(".", "/")+".class";
InputStream is = this.getClass().getResourceAsStream(classPath);
byte [] classBytes = null;
try {
classBytes = new byte[is.available()];
is.read(classBytes);
} catch (IOException e) {
e.printStackTrace();
}
return classBytes;
}
}
以上是自定义类的加载器
package com.yang.myclass.hotswap.impl;
import com.yang.myclass.hotswap.inter.ParentCalss;
public class ChildrenClass implements ParentCalss {
private String name;
public ChildrenClass(String name){
this.name = name;
}
public ChildrenClass(){
}
@Override
public void print() {
System.out.println("我是孩子1");
}
@Override
public String toString() {
return name+"1";
}
}
以上是自定义类
以下是测试类
package com.yang.myclass.hotswap;
import com.yang.myclass.hotswap.impl.ChildrenClass;
import com.yang.myclass.hotswap.inter.ParentCalss;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Logger;
public class MyHotSwapTest {
public static Logger logger = Logger.getLogger(String.valueOf(MyHotSwapTest.class));
public static void main(String[] args) throws ClassNotFoundException {
String name = "com.yang.myclass.hotswap.impl.ChildrenClass";
while (true){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_ MyClassLoader3 myClassLoader3 = new MyClassLoader3();
_ Class class3 = myClassLoader3.findClass(name);
ParentCalss childrenClass = new ChildrenClass();
System.out.println(childrenClass.toString());
}
}
}
测试类中创建对象,如果用new的话,会发现:输出的信息还是修改前的信息,而不是修改后的信息;但是如果通过class反射调用,则是最新的信息。
不过我们一般代码中都是使用new来直接创建对象,name这样的热部署意义何在?