62,614
社区成员
发帖
与我相关
我的任务
分享
public class CustomClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
System.out.println(getSystemClassLoader());
String path = this.getClass().getResource("").getPath();
File file = new File(path.substring(0, path.indexOf("class") + 8) + name.replaceAll("\\.", "/") + ".class");
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStreamReader fileInputStream = new InputStreamReader(new FileInputStream(file), StandardCharsets.ISO_8859_1);
// FileInputStream fileInputStream = new FileInputStream(file);
int b = 0;
while ((b = fileInputStream.read()) !=0) {
byteArrayOutputStream.write(b);
}
byteArrayOutputStream.close();
fileInputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
String s = new String(bytes);
System.out.println(s);
return super.defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
}
return super.findClass(name);
}
public static void main(String[] args) {
CustomClassLoader customClassLoader = new CustomClassLoader();
try {
customClassLoader.loadClass("com.me.zookeeper.test.CustomClassLoader");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
public class CustomClassLoader extends ClassLoader {
public void test(){
System.out.println("测试加载是否完成");
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
System.out.println(getSystemClassLoader());
String path = this.getClass().getResource("").getPath();
File file = new File(name);
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
int b = 0;
while ((b = fileInputStream.read()) >-1) {
byteArrayOutputStream.write(b);
}
byteArrayOutputStream.close();
fileInputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
String s = new String(bytes);
System.out.println(s);
return super.defineClass(name, bytes, 0, bytes.length);
} catch (Exception e) {
e.printStackTrace();
}
return super.findClass(name);
}
public static void main(String[] args) {
CustomClassLoader customClassLoader = new CustomClassLoader();
try {
Class<?> aClass = customClassLoader.loadClass("D:\\wok2\\zookeeper-test-main\\target\\classes\\com\\me\\zookeeper\\test\\Test.class");
System.out.println(aClass.getClassLoader());
System.out.println(aClass.getName());
Test customClassLoader1 = (Test) aClass.newInstance();
customClassLoader1.classLoaderRange();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}