Content: For any class, it is necessary to establish its uniqueness in the Java Virtual machine with the class loader that loads it, and each class loader has a separate class space. As long as the class loader of the load class is different, the two classes must be unequal (including the Equals () method, the Instanceof () method). At this point, there are two classloadertest in the virtual machine, one is loaded by the System Application class loader, and the other is loaded by our defined ClassLoader. A simple example: note the application of getResourceAsStream: Class.getresourceasstream (String Path): path does not start with "/" By default is to fetch resources from the package where it is located, with "/" The beginning is obtained from the classpath root, which is the bin start.
public class Classloadertest {public
static void Main (string[] args) throws Instantiationexception, Illegalaccessexception, classnotfoundexception {
ClassLoader myloader = new ClassLoader () {
@Override
Public class<?> loadclass (string name) throws ClassNotFoundException {
try {
string className = Name.substring (Name.lastindexof (".") + 1) + ". Class";
Returns the input stream reading the specified resource
inputstream is = GetClass (). getResourceAsStream (className);
if (is = = null) return Super.loadclass (name);
Byte[] B = new byte[is.available ()];
Is.read (b);
Converts a byte array to an instance of class classes return
defineclass (name, b, 0, b.length);
} catch (IOException e) {
throw new ClassNotFoundException (name);}}
;
Object = Myloader.loadclass ("Test". Classloadertest "). newinstance ();
System.out.println (Object.getclass ());
System.out.println (Object instanceof test. classloadertest);
}