Content: For any class, it is necessary for the class loader to load it and the class itself to establish its uniqueness in the Java Virtual machine, each class loader has a separate class space. This two class must be unequal (including the Equals () method, the Instanceof () method) as long as the class loader for the load class is different. At this point, there are two classloadertest in the virtual machine, one is loaded by the system application ClassLoader, and the other is loaded by our defined class loader. A simple example illustrates: note the application of getResourceAsStream:class.getresourceasstream (String path): path does not take "/" At the beginning, the default is to fetch resources from the package under which the class is located, starting with "/" from the classpath root, which is the bin.
public class Classloadertest {public static void main (string[] args) throws Instantiationexception, Illegalaccessexception, classnotfoundexception {ClassLoader myloader = new ClassLoader () {@Overridepublic class<? > LoadClass (String name) throws ClassNotFoundException {try {string className = Name.substring (Name.lastindexof (".") + 1) + ". Class";//returns the input stream that reads the specified resource InputStream is = GetClass (). getResourceAsStream (ClassName), if (is = = null) return Super.loa DClass (name); byte[] B = new byte[is.available ()];is.read (b);//Convert a byte array to an instance of class classes return DefineClass (name, b, 0, B.length);} catch (IOException e) {throw new classnotfoundexception (name);}}};o Bject object = Myloader.loadclass ("Test. Classloadertest "). newinstance (); System.out.println (Object.getclass ()); System.out.println (Object instanceof test. classloadertest);}}
The effect of different classloader on instanceof keyword operations in Java