示例代码:public class CustomClassLoader extends ClassLoader {
private String classPath;
public CustomClassLoader(String classPath) {
super(null);
this.classPath = classPath;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] classData = loadClassData(name);
if (classData == null) {
throw new ClassNotFoundException();
} else {
return defineClass(name, classData, 0, classData.length);
}
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
if (name.startsWith("java.")) {
return super.loadClass(name);
}
try {
return findClass(name);
} catch (ClassNotFoundException e) {
return super.loadClass(name);
}
}
private byte[] loadClassData(String className) {
String filePath = classPath + className.replace('.', '/') + ".class";
try (InputStream inputStream = new FileInputStream(filePath);
ByteArrayOutputStream byteStream = new ByteArrayOutputStream()) {
int nextValue;
while ((nextValue = inputStream.read()) != -1) {
byteStream.write(nextValue);
}
return byteStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String classPath = "path_to_classes/";
CustomClassLoader customClassLoader = new CustomClassLoader(classPath);
try {
Class<?> clazz = customClassLoader.loadClass("com.example.MyClass");
Object instance = clazz.newInstance();
System.out.println(instance.getClass().getName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}