将给定的路径内的bytecode文件进行加载, 当指定路径没有对应文件时,抛出对应的异常
public class MyClassLoader extends ClassLoader {
// 存放字节码文件的目录
private final File bytecodeFileDirectory;
public MyClassLoader(File bytecodeFileDirectory) {
this.bytecodeFileDirectory = bytecodeFileDirectory;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try (InputStream inputStream = Files.newInputStream(new File(bytecodeFileDirectory.getPath(), name + ".class").toPath())) {
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name);
}
}
public static void main(String[] args) throws Exception {
File projectRoot = new File(System.getProperty("basedir", System.getProperty("user.dir")));
MyClassLoader myClassLoader = new MyClassLoader(projectRoot);
Class testClass = myClassLoader.loadClass("className");
Object testClassInstance = testClass.getConstructor().newInstance();
String message = (String) testClass.getMethod("methodName").invoke(testClassInstance);
System.out.println(message);
}
}