0

There was an answer similar to this here: How to pass a function as a parameter in Java?

but the correct answer provided does not work. I have a class:

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         }

Inside function passMethod I'm trying to pass xMethod into testMethod, but the error I get is:

cannot find symbol
symbol : class Callable

and I'm not sure why.

Also, I tried using return type String for xMethod, can you pass a function with different return types then Integer?

Community
  • 1
  • 1
Saad
  • 26,316
  • 15
  • 48
  • 69
  • 5
    Did you `import java.util.concurrent.Callable`? (I am assuming this is the class you are looking for) – amit Sep 30 '12 at 09:08
  • @amit: the interface of 'java.util.concurrent.Callable' is ok for the case, but it would also suggest a concurrency context, which I don't necessarily see here. Something like guava's Function interface would be of more general use. – nansen Sep 30 '12 at 09:17

1 Answers1

0

I think you need to import Callable as import java.util.concurrent.Callable; and then implement it in your class before using it.

Check here:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

http://kamleshkr.wordpress.com/2009/10/02/java-threads-callable-and-future/

heretolearn
  • 6,387
  • 4
  • 30
  • 53
  • yea that made that error disappear, but where in the docs.oracle say the import path? – Saad Sep 30 '12 at 09:18
  • On the top where the name is specified you can see the package which contains it and which should be imported in your code. – heretolearn Sep 30 '12 at 09:32
  • Why a down-vote after almost 6 years of the answer ? If there is any correction or improvement required, please add a comment so that it can help others – heretolearn Aug 17 '20 at 13:18
  • @heretolearn I wasn't the downvoter, but if I had to guess, the downvoter likely objected to the suggestion that Callable has to be implemented in the class before using it. An anonymous Callable like what was being used in the question is a legitimate way to use a Callable. Personally, I wish there was a required "reason" a person has to give when they choose to downvote an answer. – Jason Thompson Jan 05 '21 at 22:01