简体   繁体   中英

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();

then in the HelloWorld Class I have my main function and another:

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:

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. if I print out someFunction, I get:

"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"

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

Exception have to be handled cause it is enforced by Callable definition .

Note that you are not passing passMe function but callable object that can call it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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