自定義類加載器

package com.jerry.demo.core;

import com.jerry.demo.model.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CustomClassLoader extends  ClassLoader {
    private final static String DEFAULT_LOAD_PATH = "G:\\devOutput\\workspace\\jerry-paas-master\\demo\\target\\classes";
    private final String classDir ;

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
       byte [] classByte =  readClassByte(name);
       if(null == classByte||classByte.length == 0){
           throw new ClassNotFoundException("cannot load this class:" + name);
       }
       return  this.defineClass(name,classByte,0,classByte.length);
       }

    public CustomClassLoader() {
        super();
        classDir = DEFAULT_LOAD_PATH;

    }
    public CustomClassLoader(String classDir) {
        super();
        this.classDir = classDir;

    }

    public CustomClassLoader(String classDir,ClassLoader parentClassParent) {
        super(parentClassParent);
        this.classDir = classDir;

    }

    private byte[] readClassByte(String className) throws ClassNotFoundException {
        className = className.replace(".","\\");
//        className = classDir + className;
        Path classPath = Paths.get(classDir,className+".class");
        if(!classPath.toFile().exists()){

            throw new ClassNotFoundException();

        }
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        try {
            Files.copy(classPath, bao);
        return bao.toByteArray();
        }catch (IOException e){

            throw new ClassNotFoundException("加載類出錯!");

        }
    }

    public static void main(String[] args) throws Exception {
        CustomClassLoader cl = new CustomClassLoader(DEFAULT_LOAD_PATH,CustomClassLoader.class.getClassLoader().getParent());
        Class clazz   = cl.findClass("com.jerry.demo.model.User");
        Method setName = clazz.getDeclaredMethod("setName", new Class[]{String.class});
        Object user = clazz.newInstance();
        setName.invoke(user,"jerry");
        System.out.println(user);
        System.out.println(user.getClass().getClassLoader());
        System.out.println(user.getClass().getClassLoader().getParent());
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章