所以情况是这样的:
private void myMethod()
{
System.out.println("Hello World"); //some code
System.out.println("Some Other Stuff");
System.out.println("Hello World"); //the same code.
}
我们不想重复我们的代码。
所描述的技术here运作良好:
private void myMethod()
{
final Runnable innerMethod = new Runnable()
{
public void run()
{
System.out.println("Hello World");
}
};
innerMethod.run();
System.out.println("Some other stuff");
innerMethod.run();
}
但是如果我想将参数传递给该内部方法呢?
例如
private void myMethod()
{
final Runnable innerMethod = new Runnable()
{
public void run(int value)
{
System.out.println("Hello World" + Integer.toString(value));
}
};
innerMethod.run(1);
System.out.println("Some other stuff");
innerMethod.run(2);
}
给了我:The type new Runnable(){} must implement the inherited abstract method Runnable.run()
虽然
private void myMethod()
{
final Runnable innerMethod = new Runnable()
{
public void run()
{
//do nothing
}
public void run(int value)
{
System.out.println("Hello World" + Integer.toString(value));
}
};
innerMethod.run(1);
System.out.println("Some other stuff");
innerMethod.run(2);
}
给了我The method run() in the type Runnable is not applicable for the arguments (int)
。
答案 0 :(得分:3)
不,这不是一种方法,而是一种匿名对象。您可以创建一个额外的方法用于对象。
Thread thread = new Thread( new Runnable()
{
int i,j;
public void init(int i, int j)
{
this.i = i;
this.j=j;
}
});
thread.init(2,3);
thread.start();
在Thread中包装runnable,然后调用start!不是run()
。
因为你无法调用匿名类的构造函数,正如@HoverCraft所指出的那样,你可以扩展一个实现Runnable
的命名类。
public class SomeClass implements Runnable
{
public SomeClass(int i){ }
}
答案 1 :(得分:2)
看起来你只想要内部方法。 Java不允许你拥有它们,因此你描述的Runnable
hack允许你排序声明一个内部方法。
但是既然你想要更多地控制它,为什么不定义你自己的:
interface Inner<A, B> {
public B apply(A a);
}
然后你可以说:
private void myMethod(..){
final Inner<Integer, Integer> inner = new Inner<Integer, Integer>() {
public Integer apply(Integer i) {
// whatever you want
}
};
// then go:
inner.apply(1);
inner.apply(2);
}
或者使用一些提供functor
个对象的库。应该有很多。 Apache Commons有一个可以使用的Functor。