简体   繁体   中英

Is it possible to define my own String class?

Is it possible to define my own String class which has the exact same name as java.lang.String? My assumption is that after I have defined it, I can use it directly or load it with a class loader.

Sorry, the code I wrote has a mistake. The String class of the parameter String[] args of the method main() was incorrectly referenced to my own defined String. That is why it occured a compile error. My working result is that we can define a class named String in my own namespace or java.lang. But since JVM has loaded the default java.lang.String, we can't load our own String and use it.

Yes, you can define that class, but you won't be able to use it. The class java.lang.String will be loaded out of the JRE at bootstrap, and you can't reload a class in the bootstrap classloader. If you try to use your own classloader, the JVM will notice that java.lang.String is already loaded and just use that one.

From the JLS section on class loading :

  • Given the same name, a good class loader should always return the same class object. (This means that the java.lang.String class that gets pulled in a bootstrap will be the authoritative class.)
  • If a class loader L1 (the bootstrap loader) delegates loading of a class C to another loader L2 (your own loader) , then for any type T ( java.lang.String ) that occurs as the direct superclass or a direct superinterface of C, or as the type of a field in C, or as the type of a formal parameter of a method or constructor in C, or as a return type of a method in C, L1 and L2 should return the same Class object. (Your own java.lang.String would be conflicting with all of the parameters and fields in anything else loaded by the bootstrap loader and would cause virtually anything past the loading of your rogue class to come crashing down with link or cast errors.)

What exactly are you trying to do, anyhow? java.lang.String has very strictly defined semantics, and changing its behavior at all would break an enormous amount of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM