java - 我可以向 String 类添加新方法吗?

标签 java string replace

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

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");

最佳答案

不,你不能。 String 类是最终类,因此您不能对其进行子类化。 Java 也无法将行为附加到现有类。 Kotlin有这个功能,但它实际上是用静态方法实现的。

关于java - 我可以向 String 类添加新方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635611/

相关文章:

java - 为什么我的邻接列表给我一个 ClassCastException?

java - 如何在一个 JPQL 查询中使用多个 JOIN FETCH

javascript - 如何仅替换匹配的正则表达式的第一个字符?

java - 如何出于测试目的关闭 ehcache

java - 时间格式最终在生产中发生变化

c - 从用户输入任意数量的字符串

c# - 使用 string.format() 函数或 LINQ 分隔字符串的最佳方法是什么?

c - 使用 strncopy 显示输出

.htaccess - 在 htaccess 中从 URL 中删除不需要的字符

mysql - 带有特殊字符的全文,用于在 json 中替换。怎么了?