简体   繁体   中英

Java Supplier/Consumer/Runnable? How to invoke method when it is supplied as a a string argument

I need a help. User supplying method with its arguments as a string. My code need to run this method.

How we can we achieve this using Supplier/Consumer/Runnable. This can be done using reflection but I want to avoid it.

import java.util.Scanner;

public class InvokeStringArgument{
    public static Supplier<String> invokeMe(String returnStr){
        return new Supplier<String>(){
            public String get(){
                System.out.println("Success");
                return returnStr;
            }
        };
    }

    public static void main(String[] args){
        //invokeMe("MyValue").get();

        System.out.println("Please enter method to invoke:");
        Scanner sc = new Scanner(System.in);
        String methodName = sc.next();
        //Need a code which will run the method when passed as a string
        //For example user input it as invokeMe("MyValue")
    }
}

Ok, got some time today to look into these pending things. Achieved solution which at this time confirms to my requirement. Used BeanShell and reflection to get this done as below

package beanshell;

import java.util.Scanner;
import java.util.function.Supplier;

import bsh.EvalError;
import bsh.Interpreter;

public class InvokeStringArgument{
    public static Supplier<String> invokeMe(String returnStr){
        return new Supplier<String>(){
            public String get(){
                System.out.println("Success: Received string '"+returnStr+"'");
                return returnStr;
            }
        };
    }

    public static void main(String[] args) throws EvalError {
        //invokeMe("MyValue").get();

        System.out.println("Please enter string to evaluate:");
        Scanner sc = new Scanner(System.in);
        String userInput = sc.next();

        Interpreter i = new Interpreter();

        Object evalSource = i.eval("public class EvalUserInput extends beanshell.InvokeStringArgument{"
                + "public void evaluserInput(){"
                + userInput+""
                + "}"
                + "}");
        try{
            Class<?> noparams[] = {};
            Class<?> cls = (Class) evalSource;
            Object obj = cls.newInstance();
            cls.getDeclaredMethod("evaluserInput", noparams).invoke(obj, null);
        } catch(Exception e){

        }
    }
}

From the console:

Please enter string to evaluate:
invokeMe("MyValue").get();
Success: Received string 'MyValue'

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