简体   繁体   English

是否可以定义我自己的String类?

[英]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? 是否可以定义自己的String类,其名称与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. main()方法的参数String [] args的String类错误地引用了我自己定义的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. 我的工作结果是,我们可以在自己的名称空间或java.lang中定义一个名为String的类。 But since JVM has loaded the default java.lang.String, we can't load our own String and use it. 但是由于JVM已加载默认的java.lang.String,所以我们无法加载自己的String并使用它。

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. java.lang.String将在引导时从JRE中加载,并且您无法在引导类加载器中重新加载类。 If you try to use your own classloader, the JVM will notice that java.lang.String is already loaded and just use that one. 如果您尝试使用自己的类加载器,则JVM将注意到java.lang.String已被加载,仅使用java.lang.String加载器即可。

From the JLS section on class loading : 有关类加载的JLS部分中

  • 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.) (这意味着在引导程序中被拉出的java.lang.String类将是权威类。)
  • 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. 如果类加载器L1 (引导加载器)将类C的加载委托给另一个加载器L2 (您自己的加载器) ,则对于任何类型为T java.lang.String的C的直接超类或直接超接口, 或者作为C中字段的类型,或者作为C中方法或构造函数的形式参数的类型,或者作为C中方法的返回类型, L1和L2应该返回相同的Class对象。 (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.) (您自己的java.lang.String将与引导加载程序加载的其他任何参数和字段冲突,并且实际上会导致流氓类加载之后的所有内容崩溃,并出现链接或强制转换错误。)

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. java.lang.String具有非常严格定义的语义,并且完全改变其行为将破坏大量的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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