我可以向 Java 中的 String 类添加新方法吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/81786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I add new methods to the String class in Java?
提问by user15546
I'd like to add a method AddDefaultNamespace()
to the String class in Java so that I can type "myString".AddDefaultNamespace()
instead of DEFAULTNAMESPACE + "myString"
, to obtain something like "MyDefaultNameSpace.myString"
. I don't want to add another derived class either (PrefixedString
for example).
我想向AddDefaultNamespace()
Java 中的 String 类添加一个方法,以便我可以键入"myString".AddDefaultNamespace()
而不是DEFAULTNAMESPACE + "myString"
, 以获得类似"MyDefaultNameSpace.myString"
. 我也不想添加另一个派生类(PrefixedString
例如)。
Maybe the approach is not good for you but I personally hate using +
. But, anyway, is it possible to add new methods to the String class in Java?
也许这种方法对您不利,但我个人讨厌使用+
. 但是,无论如何,是否可以向 Java 中的 String 类添加新方法?
Thanks and regards.
感谢致敬。
采纳答案by GustyWind
String
is a final class which means it cannot be extended to work on your own implementation.
String
是 final 类,这意味着它不能扩展到您自己的实现上。
回答by jrudolph
It is not possible, since String is a final class in Java.
这是不可能的,因为 String 是 Java 中的 final 类。
You could use a helper method all the time you want to prefix something. If you don't like that you could look into Groovy or Scala, JRuby or JPython both are languages for the JVM compatible with Java and which allow such extensions.
您可以一直使用辅助方法来为某些内容添加前缀。如果您不喜欢这样,您可以查看 Groovy 或 Scala、JRuby 或 JPython,它们都是与 Java 兼容的 JVM 语言,并且允许此类扩展。
回答by Sietse
Not possible, and that's a good thing. A String is a String. It's behaviour is defined, deviating from it would be evil. Also, it's marked final, meaning you couldn't subclass it even if you wanted to.
不可能,这是一件好事。一个字符串是一个字符串。它的行为是被定义的,偏离它就是邪恶的。此外,它被标记为 final,这意味着即使你想也不能对它进行子类化。
回答by m_pGladiator
Better use StringBuilder, which has method append() and does the job you want. The String class is final and can not be extended.
最好使用 StringBuilder,它具有 append() 方法并完成您想要的工作。String 类是最终的,不能扩展。
回答by Carl-Johan
The class declaration says it all pretty much,as you cannot inherit it becouse it's final. You can ofcourse implement your own string-class, but that is probaby just a hassle.
类声明几乎说明了一切,因为您不能继承它,因为它是最终的。您当然可以实现自己的字符串类,但这可能只是一个麻烦。
public final class String
C# (.net 3.5) have the functionality to use extender metods but sadly java does not. There is some java extension called nice http://nice.sourceforge.net/though that seems to add the same functionality to java.
C# (.net 3.5) 具有使用扩展方法的功能,但遗憾的是 java 没有。有一些名为 nice http://nice.sourceforge.net/ 的java 扩展名,尽管它似乎向 java 添加了相同的功能。
Here is how you would write your example in the Nice language (an extension of Java):
以下是使用 Nice 语言(Java 的扩展)编写示例的方法:
private String someMethod(String s)
{
return s.substring(0,1);
}
void main(String[] args)
{
String s1 = "hello";
String s2 = s1.someMethod();
System.out.println(s2);
}
You can find more about Nice at http://nice.sf.net
您可以在http://nice.sf.net 上找到有关尼斯的更多信息
回答by Martin Spamer
The Java String class is a final, making it immutable. This is for efficiency reasons and that it would be extremely difficult to logically extend without error; the implementers have therefore chosen to make it a final class meaning it cannot be extended with inheritance.
Java String 类是 final 类,使其不可变。这是出于效率的原因,并且在没有错误的情况下进行逻辑扩展将是极其困难的;因此,实现者选择使其成为最终类,这意味着它不能通过继承进行扩展。
The functionality you wish your class to support is not properly part of the regular responsibilities of a String as per the single responsibility principle, a namespace it is a different abstraction, it is more specialised. You should therefore define a new class, which includes String a member and supports the methods you need to provide the namespace management you require.
根据单一职责原则,您希望您的类支持的功能不是 String 常规职责的正确组成部分,命名空间是不同的抽象,它更专业。因此,您应该定义一个新类,其中包含 String 成员并支持提供所需命名空间管理所需的方法。
Do not be afraid to add abstractions (classes) these are the essence of good OO design.
不要害怕添加抽象(类),这些是良好 OO 设计的精髓。
Try using a class responsibility collaboration (CRC) cardto clarify the abstraction you need.
尝试使用类责任协作 (CRC) 卡来阐明您需要的抽象。
回答by Martin Spamer
You can create your own version of String class and add a method :-)
您可以创建自己的 String 类版本并添加一个方法:-)
回答by Vhaerun
Actually , you can modify the String class . If you edit the String.java file located in src.zip , and then rebuild the rt.jar , the String class will have more methods added by you . The downside is that that code will only work on your computer , or if you provide your String.class , and place it in the classpath before the default one .
实际上,您可以修改 String 类。如果编辑位于 src.zip 中的 String.java 文件,然后重建 rt.jar,则 String 类将添加更多方法。缺点是该代码只能在您的计算机上运行,或者如果您提供 String.class,并将其放在默认路径之前的类路径中。
回答by MB.
As everybody else has said, no you can't subclass String because it's final. But might something like the following help?
正如其他人所说,不,您不能将 String 子类化,因为它是最终的。但是像下面这样的东西可能有帮助吗?
public final class NamespaceUtil {
// private constructor cos this class only has a static method.
private NamespaceUtil() {}
public static String getDefaultNamespacedString(
final String afterDotString) {
return DEFAULT_NAMESPACE + "." + afterDotString;
}
}
or maybe:
或者可能:
public final class NamespacedStringFactory {
private final String namespace;
public NamespacedStringFactory(final String namespace) {
this.namespace = namespace;
}
public String getNamespacedString(final String afterDotString) {
return namespace + "." + afterDotString;
}
}
回答by Alex Miller
As everyone else has noted, you are not allowed to extend String (due to final). However, if you are feeling really wild, you can modify String itself, place it in a jar, and prepend the bootclasspath with -Xbootclasspath/p:myString.jar to actually replace the built-in String class.
正如其他人所指出的,您不能扩展 String (由于 final)。然而,如果你真的很狂野,你可以修改 String 本身,将它放在一个 jar 中,并在引导类路径前面加上 -Xbootclasspath/p:myString.jar 来实际替换内置的 String 类。
For reasons I won't go into, I've actually done this before. You might be interested to know that even though you can replace the class, the intrinsic importance of String in every facet of Java means that it is use throughout the startup of the JVM and some changes will simply break the JVM. Adding new methods or constructors seems to be no problem. Adding new fields is very dicey - in particular adding Objects or arrays seems to break things although adding primitive fields seems to work.
由于我不会深入讨论的原因,我实际上已经这样做过。您可能有兴趣知道,即使您可以替换该类,String 在 Java 的各个方面的内在重要性意味着它在 JVM 的整个启动过程中都会被使用,而某些更改只会破坏 JVM。添加新方法或构造函数似乎没有问题。添加新字段非常冒险 - 特别是添加对象或数组似乎会破坏事物,尽管添加原始字段似乎有效。