简体   繁体   English

将函数作为参数从一类传递到另一类

[英]passing function as arguments from one class to another

I have a class called HelloWorld where I create an object of Class Test test = new Test(); 我有一个名为HelloWorld的类,在其中创建类Test Test = new Test();的对象。

then in the HelloWorld Class I have my main function and another: 然后在HelloWorld类中,有我的主要功能和另一个功能:

public static int passMe(){
    System.out.println("running this function");
    return 1;
}

this is function im trying to pass. 这是我试图通过的功能。 I pass it int test using the following: 我使用以下方法通过了int测试:

test.getSomeFunction(new Callable<Integer>(){
              public Integer call(){
                  return passMe();
              }
          });

inside Test class I have: 在测试类中,我有:

    public void getSomeFunction(Callable<Integer> someFunction){
        System.out.println(someFunction);
    }

now all this works, but passMe() isn't being run, rather I don't know how to reference it. 现在所有这些工作正常,但是passMe()并未运行,而是我不知道如何引用它。 if I print out someFunction, I get: 如果我打印出someFunction,我得到:

"HelloWorld$1@35a8767"

so my question is how do I go about running the function I got passed in, if I do someFunction() I get error message "he method someFunction() is undefined for the type Test" 所以我的问题是我该如何运行传入的函数,如果我执行someFunction(),则会收到错误消息“他的方法someFunction()对于类型Test未定义”

    try {
        Integer result = callable.call();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

Exception have to be handled cause it is enforced by Callable definition . 必须处理异常,因为它由Callable定义强制执行。

Note that you are not passing passMe function but callable object that can call it. 请注意,您不是传递passMe函数,而是传递可以调用它的可调用对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM