类加载器与类全名才能确立其在JVM中的唯一性

原创
2017/06/25 21:46
阅读数 761

类加载器与类全名才能确立其在JVM中的唯一性

public class SimpleTest {
    public static void main(String[] args) throws Exception {
        /**
         * 类加载器与instanceof关系的演示
         */
        ClassLoader myLoader = new ClassLoader() {
            @Override
            public Class<?> loadClass(String name) throws ClassNotFoundException {
                try {
                    String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
                    InputStream is = getClass().getResourceAsStream(fileName); 
                    if (is == null) {
                        return super.loadClass(name);
                    }
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    return defineClass(name, b, 0, b.length);
                }
                catch (Exception e) {
                    throw new ClassNotFoundException(name);
                }
            }
        };

        Object obj = myLoader.loadClass("com.suntek.SimpleTest").newInstance();
        System.out.println(obj.getClass());
        System.out.println(obj instanceof com.suntek.SimpleTest);
    }
}

 

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部