在Java中关于一个类是否相等,是通过类的全限定名称来判断的,这里的全限定名称包括了类加载器在内
如果同一个类由不同加载器加载则判定两个类不相同(尽管二进制文件一致)
测试代码:
public class ClassLoaderTest { public static void main(String[] args) throws Exception { 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 (IOException e) { throw new ClassNotFoundException(name); } } }; Object obj = myLoader.loadClass(" org. fenixsoft. classloading. ClassLoaderTest").newInstance(); System.out.println(obj.getClass()); System.out.println( obj instanceof org.fenixsoft.classloading.ClassLoaderTest); } }