标签:exce 实例 available loader super etc row catch put
比较两个类是否"相等",只有在这两个类是由同一个类加载器加载的前提下才有意义,
否则,即使这两个类来源于同一个Class文件,被同一个虚拟机加载,只要加载他们的类加载器不同,那这两个类就必定不相等。
1 /** 2 * 类加载器与instanceof关键字演示 3 * 4 * @author zzm 5 */ 6 package org.codeman; 7 8 import java.io.*; 9 10 public class ClassLoaderTest { 11 12 public static void main(String[] args) throws Exception { 13 14 ClassLoader myLoader = new ClassLoader() { 15 @Override 16 public Class<?> loadClass(String name) throws ClassNotFoundException { 17 try { 18 String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class"; 19 InputStream is = getClass().getResourceAsStream(fileName); 20 if (is == null) { 21 return super.loadClass(name); 22 } 23 byte[] b = new byte[is.available()]; 24 is.read(b); 25 return defineClass(name, b, 0, b.length); 26 } catch (IOException e) { 27 throw new ClassNotFoundException(name); 28 } 29 } 30 }; 31 32 Object obj = myLoader.loadClass("org.codeman.ClassLoaderTest").newInstance(); 33 34 System.out.println(obj.getClass()); 35 System.out.println(obj instanceof org.codeman.ClassLoaderTest); 36 } 37 }
运行结果:
class org.codeman.ClassLoaderTest
false
标签:exce 实例 available loader super etc row catch put
原文地址:https://www.cnblogs.com/caotao0918/p/10898279.html