我正在寻找一种在 Java(版本 8)中做的好方法,它相当于 Groovy 的 with
Object
上的方法。
假设我有一个类(用 Java 完成,所以我可以在每个类中使用):
class MyClass {
private String someVar;
public void setSomeVar(String newVal) {
this.someVar = newVal;
}
public String getSomeVar() {
return this.someVar;
}
}
在 Groovy 中,我可以:
def mc = new MyClass().with {
setSomeVar('Hello World!') // Yes, I'm using an explicit setter for clearer comparison
it // return the instance
}
不过在 Java 中,我能想到的最接近的是使用双括号初始化程序:
MyClass mc = new MyClass(){{
setSomeVar("Hello World!");
}};
但是some advise against using the double brace initializer .事实上,挥之不去的引用确实引起了我的注意。
那么,还有其他选择吗?
最佳答案
java 中没有这样的构造与 groovy 的 with
等效。最接近的是提到的双括号初始值设定项。
你想达到什么目的?描述问题,也许 java 中有现成的模式可以解决它?
关于Java 等同于 groovy 的 Object with(Closure) 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757901/