OO: dependent class needs information from grandparent class
中描述了我要解决的问题 import java.util.function.Supplier;
public class SupplyMe {
private Supplier<String> supplied;
public SupplyMe(Supplier<String> supplied) {
this.supplied = supplied;
}
public void printSupplied() {
System.out.println(supplied.get());
}
public static void main(String[] args) {
String changingStr = "hi";
Supplier<String> helloStrSupplier = () -> changingStr;
SupplyMe mySupplyMe = new SupplyMe(helloStrSupplier);
mySupplyMe.printSupplied();
changingStr = "hi2";
mySupplyMe.printSupplied();
}
}
以下代码抛出
SupplyMe.java:18: error: local variables referenced from a lambda expression must be final or effectively final
Supplier<String> helloStrSupplier = () -> changingStr;
我该怎么做才能使供应商能够在运行时补充价值?
答案 0 :(得分:0)
我能够做到这一点
import java.util.function.Supplier;
public class SupplyMe {
public static String changingStr = "";
private Supplier<String> supplied;
public SupplyMe(Supplier<String> supplied) {
this.supplied = supplied;
}
public void printSupplied() {
System.out.println(supplied.get());
}
public static void main(String[] args) {
changingStr = "hi";
//Supplier<String> helloStrSupplier = changingStr;
Supplier<String> helloStrSupplier = new DynamicSupplier();
SupplyMe mySupplyMe = new SupplyMe(helloStrSupplier);
mySupplyMe.printSupplied();
changingStr = "hi2";
mySupplyMe.printSupplied();
}
static class DynamicSupplier implements Supplier<String> {
@Override
public String get() {
return changingStr;
}
}
}