java - java中的动态字符串连接

标签 java string

我想联系两个字符串。

这是我的代码

public class StringTest {

 public String concat = "";
 public String txt = "Hello  "+concat;

 protected void print() {
    System.out.println("Output: " + txt);
 }

 public static void main(String[] args) {
    StringTest tb = new StringTest();
    tb.concat = "World";
    tb.print();
  }
}

输出:你好

但我需要“Hello World”。 这可能吗?

条件: 不应重新分配变量(get/set,方法内部)

最佳答案

为了动态执行,您需要一个方法。

public class StringTest {

 public String concat = "";
 private String txt() { return "Hello  "+concat; }

 protected void print() {
    System.out.println("Output: " + txt());
 }

 public static void main(String[] args) {
    StringTest tb = new StringTest();
    tb.concat = "World";
    tb.print();
  }
}

仅当您编写赋值 = 时才会计算字段,但每次调用方法时都会计算该方法。

关于java - java中的动态字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47143443/

相关文章:

java - Python中优先级队列的优先级函数

java - 如何限制 Java Web 应用程序中的 Web 服务调用

Java - 访问内部类中的变量或为最终变量赋值

c - 在 C 中传递字符串

java - 将字符串转换为Java中的音频输入

java - 如何使用安全约束来保护部分url?

java - 如何从 genericReturnType 创建实例

java - 在Java中如何找到两个字符串之间所有重叠的短语?

python - 将数字分解为其他数字

c# - 无法在 asp mvc 中隐式转换类型“System.Collections.Generic.List”