Java 我可以向类字符串添加新方法吗?
我会解释我自己,我想在String类中添加一个replaceLast,这可能吗?目前我正在使用一种自制的方法,即:Java 我可以向类字符串添加新方法吗?,java,string,replace,Java,String,Replace,我会解释我自己,我想在String类中添加一个replaceLast,这可能吗?目前我正在使用一种自制的方法,即: public static String replaceLast(String string, String toReplace, String replacement) { int pos = string.lastIndexOf(toReplace); if (pos > -1) { retu
public static String replaceLast(String string, String toReplace, String replacement) {
int pos = string.lastIndexOf(toReplace);
if (pos > -1) {
return string.substring(0, pos) + replacement + string.substring(pos + toReplace.length(), string.length());
} else {
return string;
}
}
是否有任何方法可以使用这种方法,如:
String str = "Hello World";
str.replaceLast("l", "");
//being the first String the one to be replaced and the second one the replacement
就像它被使用一样:
String str = "Hello World";
str.replaceFirst("o", "e");
不,你不能。字符串类是最终类,所以不能将其子类化。Java也不能将行为附加到现有类。Kotlin有这个特性,但它实际上是用静态方法实现的。不,你不能修改
String
类或任何JRE类,而且String
是不可变的,所以你的设计无论如何都是错误的。你的意思是str=str.replaceFirst(“o”,“e”)你说得对,可怕的袋熊。User207421先生,你说“字符串是不可变的,所以你的设计是错误的”是什么意思?我的方法replaceLast是错误的,还是将该方法添加到类字符串中的想法?您的想法是,调用str.replaceLast(…)
而不存储结果值,就像您在示例中所做的那样,将更新任何错误的方法。