Home > Back-end > Questions about the custom class loader
Questions about the custom class loader
Time:05-09
Public class CustomClassLoader extends this {
@ Override Protected Class<?> FindClass (String name) throws ClassNotFoundException { System. The out. Println (getSystemClassLoader ()); String path=this. GetClass (). GetResource (" "). GetPath (); The File File=new File (path. The substring (0, the path indexOf (" class ") + 8) + name. The replaceAll (" \ \ ", "/") + ". The class "); Try { ByteArrayOutputStream ByteArrayOutputStream=new ByteArrayOutputStream (); InputStreamReader fileInputStream=new InputStreamReader (new fileInputStream (file), StandardCharsets. ISO_8859_1); //a FileInputStream FileInputStream=new FileInputStream (file); Int b=0; While ((b=a fileInputStream. Read ())!=0) { ByteArrayOutputStream. Write (b); } ByteArrayOutputStream. Close (); FileInputStream. Close (); Byte [] bytes=byteArrayOutputStream. ToByteArray (); String s=new String (bytes); System.out.println(s); Return super. DefineClass (name, bytes, 0, bytes. The length). } the catch (Exception e) { e.printStackTrace(); } Return super. FindClass (name); }
Public static void main (String [] args) { CustomClassLoader CustomClassLoader=new CustomClassLoader (); Try { CustomClassLoader. LoadClass (" com. Me. The zookeeper. Test. CustomClassLoader "); } the catch (a ClassNotFoundException e) { e.printStackTrace(); } } }
When running the code customClassLoader. LoadClass (" com. Me. The zookeeper. Test. CustomClassLoader "), no call custom findClass () method
CodePudding user response:
Class loader to load this class?
CodePudding user response:
https://blog.csdn.net/weixin_30342639/article/details/105389653, the nature of the class loader is initialized the JVM when loading the references to classes, methods to stack memory, heap memory, and stack method, such as you wrote a xxxUtil class, you don't want AppClassLoader load it, but through a custom class loaders loading xxxUtil, then the need to define the class loader, -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- And your written above is loaded himself, it must be through the parent class loader loads, but also in the same class, source CustomClassLoader. In Java, not into the custom of the loader, CustomClassLoader. LoadClass (" com. Me. The zookeeper. Test. CustomClassLoader "); The loadClass is to load the others