Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,855 questions

51,776 answers

573 users

How to pass a runnable procedure (a function) as a parameter and run it in Java

2 Answers

0 votes
public class Main {
    // Generic method that accepts a functional interface
    static void control(Runnable f) {
        f.run();
    }

    static void say() {
        System.out.println("abcd");
    }

    public static void main(String[] args) {
        control(Main::say); // Pass method reference
    }
}

 
 
/*
run:

abcd

*/

 



answered May 21, 2025 by avibootz
0 votes
import java.util.concurrent.Callable;

public class Main {
    // Generic method that accepts a Callable and executes it
    public static <T> T control(Callable<T> f) throws Exception {
        return f.call();
    }

    public static String say() {
        return "abcd";
    }

    public static void main(String[] args) {
        try {
            // Using a method reference
            String result = control(Main::say);
            System.out.println(result); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 
 
/*
run:

abcd

*/

 



answered May 21, 2025 by avibootz
...