现在的位置: 首页 > 综合 > 正文

自定义类的加载

2015年07月25日 ⁄ 综合 ⁄ 共 1201字 ⁄ 字号 评论关闭

首先创建一个类ClassLoaderDemo

public static void main(String[] args) throws Exception {
        MyClassLoader2 mc = new MyClassLoader2();
        Class cls = mc.findClass("cn.itcast.demo.Person");                                   //这里代表所以去加载的是Person

        Object o = cls.newInstance();
        System.out.println("toString"+o+","+o.getClass().getClassLoader());
    }

在创建一个MyClassLoader2

public class MyClassLoader2 extends ClassLoader{
    public Class<?> findClass(String name) throws ClassNotFoundException{
            String classNameWithPackge = name;
            Class<?> cls=null;
            try {
                name = name.replace(".","/");        //将所有.  全部替换掉为  /
                name+=(".class");
                URL url = MyClassLoader2.class.getClassLoader().getResource(name);    //获取.class文件
                File file = new File(url.getPath());
                InputStream in = new FileInputStream(file);                   //转为字节流
                //读取.class文件的字节码
                byte[] b = new byte[in.available()];    //直接声明大小
                int len = in.read(b);  
                cls = defineClass(classNameWithPackge,b,0,len);                //将其转为Class实例,然后就可以编译了
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        return cls;
    }
}

抱歉!评论已关闭.