简体   繁体   中英

Passing methods (or voids) to Java ArrayList

I was wondering if there is any way to pass "void" objects to a Java ArrayList.

for example, I want to pass a void object "public void doThis()" to an array list by referencing it as list1.put(doThis());

When passing a reference to a method to an Array List Object I get the following:

The method add(Object) in the type ArrayList<Object> is not applicable for the arguments (void)

I am trying to make a class which can take a ArrayList of references to methods in other classes and iterate to execute the methods in threads.


package asWebRest.shared;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ThreadRipper {

    private int maxThreads = 4;
    private int maxThreadsHost = 8;


    public void runProcess(String pString) {
        System.out.println(" --> Running [ "+pString+" ]");
        String s = null;
        String[] pArray = { "bash", "-c", pString };
        try { 
            Process p = new ProcessBuilder(pArray).start();
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((s = stdInput.readLine()) != null) { System.out.println(s); }
            while ((s = stdError.readLine()) != null) { System.out.println(s); }
            p.destroy();
        }
        catch (IOException e) { e.printStackTrace(); }
        System.out.flush();
    }

    public String runProcesses() {

        boolean pool = false;
        WebCommon wc = new WebCommon();
        ArrayList<Object> threadList = new ArrayList<Object>();
        threadList.add(runProcess("ls -l"));
        threadList.add(runProcess("ls -s"));
        threadList.add(runProcess("ls -al"));

        String runResults = "";
        int procLoop = 0;
        int inPool = 0;

        for(int i = 0; i < threadList.size(); i++) {            
            Object exTask = threadList.get(i);  
            if(!pool) {
                if(inPool < maxThreads) {
                    runResults += "Loop [" + procLoop + "] Thread [" + inPool + "]: " + exTask + "\n";
                    inPool++;
                } else {
                    procLoop++;
                    inPool = 0;
                }
            } else {
                runResults += "Pool Thread [" + inPool + "]: " + exTask + "\n";
                inPool++;
            }       
        }

        return runResults;

    }

    public int getMaxThreads() { return maxThreads; }
    public int getMaxThreadsHost() { return maxThreadsHost; }

}

What you are doing is adding the return of runProcess("ls -l") instead of reference to the runProcess , and since runProcess returns nothing, Java shows an error that you can't add void to the list.

You need use a list of Runnable s.

List<Runnable> processes = new ArrayList<Runnable>();

Add it to the list this way,

processes.add(()->runProcess("ls -l"));

Then you can do whatever you choose with the list of processes,

for(Runnable process : processes) { 
   process.run();// You can other fancy stuff here.
   new Thread(process).start(); // eg : spawn in new thread.
}

Why not try using java.lang.reflect.Method and all the relevant information and pass it to your list?

for example, if you want to execute a method wich you know the class it belongs to, name, and instance if needed, and arguments, as well as the return type, you could do this:

Method myMethod = myClass.class.getMethod(methodName, args...);
Object[] args = myArgs... //fill with the relevant data

Set up a DTO and add to your Array.

Then when you want to execute it

myMethod .invoke(instance, args)

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