我想联系两个字符串。
这是我的代码
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/