1.继承ClassLoader父类自定义类加载器
    2.自定义类加载器,默认partner为AppClassLoader
    初始化自定义类加载器时,调用父类ClassLoader的构造方法

    1. protected ClassLoader() {
    2. this(checkCreateClassLoader(), getSystemClassLoader());
    3. }
    4. public static ClassLoader getSystemClassLoader() {
    5. initSystemClassLoader();
    6. if (scl == null) {
    7. return null;
    8. }
    9. SecurityManager sm = System.getSecurityManager();
    10. if (sm != null) {
    11. checkClassLoaderPermission(scl, Reflection.getCallerClass());
    12. }
    13. return scl;
    14. }
    15. private static synchronized void initSystemClassLoader() {
    16. if (!sclSet) {
    17. if (scl != null)
    18. throw new IllegalStateException("recursive invocation");
    19. sun.misc.Launcher l = sun.misc.Launcher.getLauncher();//获取jvm启动器实例
    20. if (l != null) {
    21. Throwable oops = null;
    22. scl = l.getClassLoader();//获取AppClassLoader
    23. //删除其他逻辑代码
    24. }
    25. }
    26. }
    1. public class MyClassLoader extends ClassLoader {
    2. private String classPath;
    3. public MyClassLoader(String classPath) {
    4. this.classPath = classPath;
    5. }
    6. private byte[] loadByte(String name) throws Exception {
    7. name = name.replaceAll("\\.", "/");
    8. FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
    9. int available = fis.available();
    10. byte[] data = new byte[available];
    11. fis.read(data);
    12. fis.close();
    13. return data;
    14. }
    15. protected Class<?> findClass(String name) throws ClassNotFoundException {
    16. try {
    17. byte[] data = loadByte(name);
    18. return defineClass(name, data, 0, data.length);
    19. } catch (Exception e) {
    20. throw new ClassNotFoundException();
    21. }
    22. }
    23. }