【发布时间】:2012-09-30 09:05:58
【问题描述】:
这里有一个类似的答案: How to pass a function as a parameter in Java?
但提供的正确答案不起作用。我有一堂课:
public class randomClass {
2
3 public String name;
4 private int x;
5 private boolean y;
6
7 public randomClass(String name){
8 this.name = name;
9 setAttributes(1,true, "test");
10 System.out.println(x + "," + y);
11 }
...
21
22 public int xMethod(){
23 return 1;
24 }
25
26 public void passMethod(){
27 testMethod(new Callable<Integer>() {
28 public Integer call(){
29 return xMethod();
30 }
31 });
32 }
33
34 public void testMethod(Callable<Integer> myFunc){
35
36 }
在函数passMethod 内部我试图将xMethod 传递给testMethod,但我得到的错误是:
找不到符号
符号:类可调用
我不知道为什么。
另外,我尝试为 xMethod 使用返回类型 String,你能传递一个返回类型与 Integer 不同的函数吗?
【问题讨论】:
-
你
import java.util.concurrent.Callable了吗? (我假设这是您正在寻找的课程) -
@amit: 'java.util.concurrent.Callable' 的接口对于这种情况来说是可以的,但它也会建议一个并发上下文,我不一定在这里看到。像番石榴的 Function 接口这样的东西会更通用。
标签: java