天天看點

自己手寫一個類加載器demo

 1,先寫一個簡單的java檔案,儲存在桌面。

public class A{
	static{
		System.out.println("hello , hcmony !");
	}
}
           

2.用javac編譯成 A.class 

javac A.java 

自己手寫一個類加載器demo

 3.建立自己的ClassLoader類,如下:

package com.hcmony;

import java.io.*;

/**
 * <h3>類的基本描述</h3>
 *
 * @author hcmony
 * @since V1.0.0, 2021/2/19 10:39
 */
public class ClassLoaderTest extends ClassLoader {
    private String classloaderName;
    private String path ;

    public ClassLoaderTest(String classloaderName, String path) {
        this.classloaderName = classloaderName;
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name,b,0,b.length);
    }

    private byte[] loadClassData(String name) {
        name = path + name + ".class";
        InputStream in = null;
        ByteArrayOutputStream out = null;

        try {
            in = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            int i = 0;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
        }catch (Exception e){
            e.printStackTrace();

        }finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return out.toByteArray();
    }

   
}
           

4.寫一個測試的方法

public static void main(String[] args)
            throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        ClassLoaderTest classloader = new ClassLoaderTest("classLoaderTest", "/Users/hcmony/Desktop/");
        Class c = classloader.loadClass("A");
        System.out.println(c.getClassLoader());
        System.out.println(c.getClassLoader().getParent());
        System.out.println(c.getClassLoader().getParent().getParent());
        c.newInstance();
    }
           

 5.結果如下:

[email protected]
[email protected]
[email protected]
hello , hcmony !