Java提供的界面還有Callable
Runnable
方法run()
允許將功能作爲對象傳遞。 (任何其他接口都可以這樣做,但Runnable
是Java中的標準)。你可以做這樣的事情:
final HashSet<Runnable> set = new HashSet<>();
set.add(new Runnable() {
public void run() {
milk(); //will execute milk()
}
});
set.add(new Runnable() {
public void run() {
doSomething(); //will execute doSomething()
}
});
// and so on
for(Runnable r : set) {
r.run(); //will execute each Runnable in the set
}
這種方法會執行Runnable
及其run()
方法匿名類。在集合中執行的每個Runnable
的run()
方法將被調用,並且在這些run()
方法中,您可以執行任何您想要的操作。在這種情況下,您只需調用另一個函數。
請參閱this documentation的匿名類。有一個簡單的符號叫做lambda-expressions。但是如果你只是在學習Java,你應該首先了解匿名類。
UPDATE:爲了準確地去除Runnable
牛奶,你可以這樣做:
final HashSet<Runnable> set = new HashSet<>();
//store the runnable in variable so that we know which runnable to remove afterwards
final Runnable milk = new Runnable() {
public void run() {
milk(); //will execute milk()
}
};
//add the runnable as usual
set.add(milk);
//add some other runnables
set.add(new Runnable() {
public void run() {
doSomething(); //will execute doSomething()
}
});
// and so on
for(Runnable r : set) {
r.run(); //will execute each Runnable in the set
}
set.remove(milk); //remove the Runnable we created first
閱讀有關[反思](http://docs.oracle.com/javase/教程/反映/)。 – Maroun 2015-02-08 14:59:10
@MarounMaroun:我認爲使用Runnables或Callables等接口集合會更好地服務原始海報。 – 2015-02-08 15:00:46
你可以使用Java 8和方法引用,比如'MyClass :: milk'和東西。 https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html和Runnable/Callable也適用於您的案例,我想.. – EpicPandaForce 2015-02-08 15:13:51