Java Pass Method as Parameter

后端 未结 16 1016
滥情空心
滥情空心 2020-11-22 02:17

I am looking for a way to pass a method by reference. I understand that Java does not pass methods as parameters, however, I would like to get an alternative.

I\'ve

16条回答
  •  逝去的感伤
    2020-11-22 02:54

    I appreciate the answers above but I was able to achieve the same behavior using the method below; an idea borrowed from Javascript callbacks. I'm open to correction though so far so good (in production).

    The idea is to use the return type of the function in the signature, meaning that the yield has to be static.

    Below is a function that runs a process with a timeout.

    public static void timeoutFunction(String fnReturnVal) {
    
        Object p = null; // whatever object you need here
    
        String threadSleeptime = null;
    
        Config config;
    
        try {
            config = ConfigReader.getConfigProperties();
            threadSleeptime = config.getThreadSleepTime();
    
        } catch (Exception e) {
            log.error(e);
            log.error("");
            log.error("Defaulting thread sleep time to 105000 miliseconds.");
            log.error("");
            threadSleeptime = "100000";
        }
    
        ExecutorService executor = Executors.newCachedThreadPool();
        Callable task = new Callable() {
            public Object call() {
                // Do job here using --- fnReturnVal --- and return appropriate value
                return null;
            }
        };
        Future future = executor.submit(task);
    
        try {
            p = future.get(Integer.parseInt(threadSleeptime), TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error(e + ". The function timed out after [" + threadSleeptime
                    + "] miliseconds before a response was received.");
        } finally {
            // if task has started then don't stop it
            future.cancel(false);
        }
    }
    
    private static String returnString() {
        return "hello";
    }
    
    public static void main(String[] args) {
        timeoutFunction(returnString());
    }
    
        

    提交回复
    热议问题