3 回答
TA貢獻1851條經驗 獲得超5個贊
在Java中,最接近這樣做的方法可能是構造過程中的雙花括號習慣用法。
Foo foo = new Foo() {{
bar();
reset(true);
myVar = getName(); // Note though outer local variables must be final.
}};
另外,this可以將返回的方法鏈接在一起:
myName =
foo
.bar()
.reset(true)
.getName();
哪里bar和reset方法返回this。
但是,想要這樣做往往表示該對象沒有足夠豐富的行為。嘗試將其重構為被調用的類。也許有不止一個班試圖脫身。
TA貢獻1797條經驗 獲得超4個贊
使用Java 8 lambda可以使您非常接近,但缺點是無法修改局部變量。
聲明此方法:
static <T> void with(T obj, Consumer<T> c) {
c.accept(obj);
}
因此,您可以使用:
Window fooBarWindow = new Window(null);
String mcHammer = "Can't Touch This";
with(fooBarWindow, w -> {
w.setAlwaysOnTop(true);
w.setBackground(Color.yellow);
w.setLocation(300, 300);
w.setTitle(mcHammer); // can read local variables
//mcHammer = "Stop!"; // won't compile - can't modify local variables
});
使用匿名類也可以這樣做,但不是很干凈。
添加回答
舉報
