一、被加载的测试类
1.将被加载的测试类放到d盘test目录下,然后其他子目录按照测试的包名创建,完整路径值这样的:D:\test\com\example\jvm\demo
2.测试类如下:
package com.example.jvm.demo;
import java.io.PrintStream;
public class Hello
{
public void show()
{
System.out.println("hello");
}
}
二、自定义加载器
自定义类加载器,主要是重写ClassLoader中的findClass方法;因为当所有的类加载器都加载不到class文件时,就要调用findClass方法,而ClassLoader中的findClass方法是直接抛异常的,所以需要重写findClass方法加载我们制定的文件,代码如下:
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
自定义的类加载器:
package com.example.jvm.demo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
public class JVM_002_ClassLoader extends ClassLoader {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
File file = new File("d:/test/"+name.replace(".","/").concat(".class"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
FileInputStream fis = new FileInputStream(file);
int b = 0;
while((b = fis.read()) != -1) {
baos.write(b);
}
byte[] bytes = baos.toByteArray();
baos.close();
fis.close();
return defineClass(name,bytes,0,bytes.length);
}catch (IOException e){
e.printStackTrace();
}
return super.findClass(name);
}
public static void main(String[] args) throws Exception{
ClassLoader l = new JVM_002_ClassLoader();
Class<?> aClass = l.loadClass("com.example.jvm.demo.Hello");
Object o = aClass.newInstance();
Method method = aClass.getMethod("show");
method.invoke(o);
}
}
三、测试结果