Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我可以向类字符串添加新方法吗?_Java_String_Replace - Fatal编程技术网

Java 我可以向类字符串添加新方法吗?

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

我会解释我自己,我想在String类中添加一个replaceLast,这可能吗?目前我正在使用一种自制的方法,即:

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”)str.replaceLast(…)
而不存储结果值,就像您在示例中所做的那样,将更新任何错误的方法。