码迷,mamicode.com
首页 > 其他好文 > 详细

自定义ClassLoader

时间:2017-12-31 13:36:49      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:object   sse   dex   map   replace   turn   prot   imp   put   

自定义classloader

MapleClassLoader

package com.maple;

import java.io.*;

public class MapleClassLoader extends ClassLoader {

    private String path = "E:\\Workspaces\\loader\\target\\classes\\";

    public MapleClassLoader(String path){
        this.path = path ;
    }

    public MapleClassLoader(ClassLoader parent,String path){
        super(parent);
        this.path = path;
    }


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


    /*private byte[] loadClassData(String name) {
        try {
            name = name.replaceAll(".", "\\");
            FileInputStream is = new FileInputStream(new File(path + name + ".class"));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = is.read()) != -1) {
                bos.write(b);
            }
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        try {
            String fileName = name.replaceAll("\\.", "\\/");
            FileInputStream is;
            try {
                is = new FileInputStream(new File(path + fileName + ".class"));
            } catch (Exception e) {
                is = null;
            }


            if (is == null) {
                return super.loadClass(name);
            }

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int b;
            while ((b = is.read()) != -1) {
                bos.write(b);
            }
            byte[] data = bos.toByteArray();

            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            throw new ClassNotFoundException(name);
        }
    }
}

测试

public class Demo1 {

    public static void main(String[] args) throws Exception {
        MapleClassLoader mc = new MapleClassLoader(Thread.currentThread().getContextClassLoader(),"E:\\Workspaces\\loader\\target\\classes\\");
        Object obj = (Object)mc.loadClass("com.maple.Demo1").newInstance();
        System.out.println("load: "+ obj.getClass());
        System.out.println("local: "+ Demo1.NUM);
        System.out.println(obj instanceof Demo1);
    }

    private static int NUM = 1;

    private static Integer addNum(){
        return NUM++;
    }
}

测试结果

load: class com.maple.Demo1
local: 1
false

自定义ClassLoader

标签:object   sse   dex   map   replace   turn   prot   imp   put   

原文地址:https://www.cnblogs.com/leihuazhe/p/8157506.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!