Java教程

自定义类加载器

本文主要是介绍自定义类加载器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package com.wangbiao.security;

public class Boy {
    public void getBoy(){
        System.out.println("上帝是个宝贝");
    }

    public static Object getBoyObject(){
        return new Object();
    }

    private static Object getStaticBoyObject(){
        return new Object();
    }
}
package com.wangbiao.security;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class MyClassLoader extends ClassLoader {
    static {
        System.out.println(">>>>>>>>>>>");
    }


    public String getRoot() {
        return root;
    }

    public void setRoot(String root) {
        this.root = root;
    }

    private String root;
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = getByte(name);
        if (classData == null) {
            throw new ClassNotFoundException();
        } else {
            return defineClass(name, classData, 0, classData.length);
        }
    }


    private byte[] getByte(String name) {
        String fileName = ".\\target\\classes\\com\\wa\\security\\"
                + name.replace('.', File.separatorChar) + ".class";
        FileInputStream fis;
        try {
            fis = new FileInputStream(fileName);
            //自行处理加密解密等逻辑
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                bao.write(len);
            }
            bao.flush();
            return bao.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

package com.wangbiao.security;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        MyClassLoader myClassLoader=new MyClassLoader();
        myClassLoader.setRoot("自定义编译路径");
        Class<?> aClass = myClassLoader.loadClass("Boy");
        Object o = aClass.newInstance();
        Method getBoy = aClass.getMethod("getBoy");
        getBoy.invoke(o);
    }
}

 

这篇关于自定义类加载器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!