我从网络获取字节码。我将字节数组转换为类
package l2soft.utils;
public final class CustomClassLoader extends ClassLoader {
public static CustomClassLoader _instance;
public static CustomClassLoader getInstance() {
return _instance;
}
public void defineCustomClass(byte[] bytecode) {
Class<?> clazz = defineClass(null, bytecode, 0, bytecode.length);
resolveClass(clazz);
}
}
但是当应用程序启动时,无法找到派生类。
The import test.Test1 cannot be resolved
(与收到的课程一起编译)
注意:我不知道类文件名。我不需要请求一个类,服务器自己发送
升级版:
package l2soft.utils;
import java.util.HashMap;
import java.util.Map;
public final class CustomClassLoader extends ClassLoader {
private Map<String, Class<?>> cache;
public static CustomClassLoader _instance;
public static CustomClassLoader getInstance() {
return _instance;
}
public CustomClassLoader(ClassLoader parent) {
super(ClassLoader.getSystemClassLoader());
_instance = this;
cache = new HashMap<String, Class<?>>();
}
public void defineCustomClass(byte[] bytecode) {
Class<?> clazz = defineClass(null, bytecode, 0, bytecode.length);
resolveClass(clazz);
cache.put(clazz.getName(), clazz);
}
@Override
public synchronized Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> result = cache.get(name);
if(result == null)
super.findClass(name);
return result;
}
}
这是我的自定义类加载器。SomeClass 由这个类加载器和 tes.Test1 加载。但我看到错误:import test.Test1 无法解决。此 CustomClassLoader 设置为默认加载程序 (-Djava system.loader=l2soft.utils.CustomClassLoader)