【发布时间】:2012-11-20 03:56:07
【问题描述】:
所以情况是这样的:
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)。
【问题讨论】:
-
好的,我完全不清楚为什么这涉及可运行程序和大概的多线程 - 你能澄清一下吗?
-
您知道
Runnable是用于multithreading的预定义接口吗?为什么不创建自己的界面? -
这是我发现在 Java 中使用方法中的方法的唯一解决方案。
-
但是你为什么要方法中的方法呢?
-
Runnable 不是为此目的而设计的 (docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html)。您是否尝试定义自己的界面而不是使用 Runnable ?这样,您将拥有所需的所有纬度。
标签: java methods abstract overriding