根据输入参数调用不同的方法

时间:2014-02-18 14:15:27

标签: java

请给我一个建议和示例,当我应该使用Map调用不同的方法到传入的参数时,我可以如何实现这种情况。

public String mainMethod(Int count) {
    if (count == 1) { return myMethod }
    else if (count == 2) { return myMethod2 }
    else if (count == 3) { return myMethod3 }
}

public String myMethod1() {
    ..............  
} 

public String myMethod2() {
    ..............  
} 

public String myMethod3() {
    ..............  
} 

6 个答案:

答案 0 :(得分:3)

您在评论中指出的问题是:

Map<Integer, Callable> map = new HashMap<>();
map.put(1, new Callable() {
    public Object call() throws Exception {
        //code for argument 1
        return null;
    }
});
map.put(2, new Callable() {
    public Object call() throws Exception {
        //code for argument 2
        return null;
    }
});
map.put(3, new Callable() {
    public Object call() throws Exception {
        //code for argument 3
        return null;
    }
});

现在您可以将其用作

map.get(count).call();

答案 1 :(得分:1)

您应该使用具有不同方法调用的描述性名称的enum,并将myMethod设为私有。例如,像:

public enum Method { GOOD, BAD, UGLY; }

public String mainMethod(Method method) {
    switch (method) {
    case GOOD: return myMethod1();
    case BAD:  return myMethod2();
    case UGLY: return myMethod3();
    }
}

private String myMethod1() { ... };
private String myMethod2() { ... };
private String myMethod3() { ... };

答案 2 :(得分:0)

您需要为每个可能的整数输入填充匿名类的静态Map<Integer, Callable>,然后return MAP.get(count).call();

答案 3 :(得分:0)

public abstract class MethodImplementation
{
    private static final Map<Integer, SomeInterface>    IMPLEMENTATION_MAP;

    static
    {
        IMPLEMENTATION_MAP  = new HashMap<>();

        IMPLEMENTATION_MAP.put( 1, new Implementation1() );
        IMPLEMENTATION_MAP.put( 2, new Implementation2() );
        IMPLEMENTATION_MAP.put( 3, new Implementation3() );

    }

    public static interface SomeInterface
    {
        public String Method();

    }

    public static String Selector( int count_ )
    {
        String          result          = null;
        SomeInterface   implementation  = IMPLEMENTATION_MAP.get( count_ );

        if( null != implementation )
        {
            result  = implementation.Method();

        }

        return result;

    }

    public static class Implementation1 implements SomeInterface
    {
        @Override
        public String Method()
        {
            String  result  = "Method1";

            return result;

        }

    }

    public static class Implementation2 implements SomeInterface
    {
        @Override
        public String Method()
        {
            String  result  = "Method2";

            return result;

        }

    }

    public static class Implementation3 implements SomeInterface
    {
        @Override
        public String Method()
        {
            String  result  = "Method3";

            return result;

        }

    }

    private MethodImplementation()
    {

    }

}

用法:

String  res = MethodImplementation.Selector( i );

答案 4 :(得分:0)

你也可以使用反射。

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class InvokeMethod {

    /**
     * Map of input integer to method name to be invoked.
     */
    private final static Map<Integer, String> methods = new HashMap<>();
    static {
        methods.put(1, "method1");
        methods.put(2, "method2");
        methods.put(3, "method3");
    }

    /**
     * @param count Method identifier.
     */
    public static void mainMethod(int count) {
        String methodName = methods.get(count);
        Method method = null;

        try {
            // Check the javadoc of the following method to see how to
            // handle multiple arguments
            method = InvokeMethod.class.getDeclaredMethod(methodName, int.class);
        } catch (NoSuchMethodException e) {
            System.out.println("ERROR: Method not found: " + methodName);
            System.exit(1);
        } catch (SecurityException e) {
            System.out.println("ERROR: Unable to access the method: " + methodName);
            System.exit(1);
        }

        try {
            // Invoking statically, so passing null.
            // Else the class instance needs to be passed.
            // Go through the javadoc of the following method to see
            // how to handle multiple arguments.
            method.invoke(null, 5);
        } catch (InvocationTargetException | IllegalAccessException e) {
            System.out.println("ERROR: Unable to access the method: " + methodName);
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("ERROR: Incorrect arguments passed: " + methodName);
            System.exit(1);
        }
    }

    /**
     * Prints the number as is.
     * @param in Input integer.
     */
    public static void method1(int in) {
        System.out.println(in);
    }

    /**
     * Doubles the number and prints it.
     * @param in Input integer.
     */
    public static void method2(int in) {
        System.out.println(in * 2);
    }

    /**
     * Squares the number and prints it.
     * @param in Input integer.
     */
    public static void method3(int in) {
        System.out.println(in * in);
    }
}

答案 5 :(得分:0)

向地图添加callables的解决方案看起来不错,但现在使用Java 8可以简化为:

Map<Integer, Callable> map = new HashMap<>();
map.put(1, () -> null);
map.put(2, () -> 33);
map.put(3, () -> 66);

或者如果您想使用该类中定义的其他方法:

Map<Integer, Callable> map = new HashMap<>();
map.put(1, ClassName::myMethod1);
map.put(2, ClassName::myMethod2);
map.put(3, ClassName::myMethod3);

然后调用与上一个解决方案相同的方法:map.get(count).call();