我搜索了这个,但遗憾的是找不到匹配项,我在这样的方法中有local anonymous inner class
: -
new Object(){
public void open(){
// do some stuff
}
public void dis(){
// do some stuff
}
};
2 methods
内有(open,dis)
,我知道如果我想使用其中任何一个就行了
new Object(){
public void open(){
// do some stuff
}
public void dis(){
// do some stuff
}
}.open()
现在我的问题是如果我想同时调用这两种方法怎么办?
答案 0 :(得分:6)
您可以创建如下界面:
interface MyAnonymous {
MyAnonymous open();
MyAnonymous dis(); //or even void here
}
new MyAnonymous(){
public MyAnonymous open(){
// do some stuff
return this;
}
public MyAnonymous dis(){
// do some stuff
return this;
}
}.open().dis();
编辑----
正如@Jeff指出的那样,只有在分配了引用时才需要接口。 实际上,以下解决方案(由@JamesB引起)完全有效:
new MyObject(){
public MyObject open(){
// do some stuff
return this;
}
public MyObject dis(){
// do some stuff
return this;
}
}.open().dis();
但这不会编译:
MyObject myObject = new MyObject(){
public MyObject open(){
// do some stuff
return this;
}
public MyObject dis(){
// do some stuff
return this;
}
};
myObject.open().dis(); //not compiling since anonymous class creates a subclass of the class
答案 1 :(得分:1)
new MyObject(){
public MyObject open(){
// do some stuff
return this;
}
public MyObject dis(){
// do some stuff
return this;
}
}.open().dis();
答案 2 :(得分:1)
如果要从匿名类调用方法,则意味着它扩展了超类或实现了接口。所以你可以简单地存储在父实例的引用中,然后调用所有契约的方法:
interface MyAnonymous {
void open();
void dis();
}
MyAnonymous anon = new MyAnonymous () {
public void open(){
// do some stuff
}
public void dis(){
// do some stuff
}
};
anon.open();
anon.dis();