2017-09-14 29 views
-1

所以我在下面有下面的代码,其他地方叫Operators Op = new Operators()。但是,我在getMethod调用中遇到错误。我承认我并不完全知道如何使用它,并通过阅读其他人的代码来获得这个结果,所以任何帮助都会很棒。谢谢。Class.getMethod不能正常工作

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

public class Operators { 
    static Map<String, Method> METHODS = new HashMap<String, Method>(); 
    String ADD = "+"; String MULTIPLY = "*"; String SUBTRACT = "-"; String DIVIDE = "/"; 
    private static Class[] inputTypes = {Float.class, Float.class}; 

    Operators() throws NoSuchMethodException, SecurityException { 
     METHODS.put(ADD, getMethod("add")); 
     METHODS.put(MULTIPLY, getMethod("multiply")); 
     METHODS.put(SUBTRACT, getMethod("subtract")); 
     METHODS.put(DIVIDE, getMethod("divide")); 
    } 

    static Method getMethod(String s) throws NoSuchMethodException { 
     return Operators.class.getMethod(s, inputTypes); 
    } 

    public static float add(float x, float y) { 
     return x+y; 
    } 

    public static float multiply(float x, float y) { 
     return x*y; 
    } 

    public static float subtract(float x, float y) { 
     return x-y; 
    } 

    public static float divide(float x, float y) { 
     return x/y; 
    } 
} 

编辑。在getMethod方法中引用的行是return Operators.class.getMethod(s, inputTypes);

+0

你会得到什么错误? –

+0

@GergelyBacso NoSuchMethodException。 –

+0

引用的行是'return Operators.class.getMethod(s,inputTypes);''getMethod'方法内部''。 –

回答

3

它可能给我怎么帮你一次,我明白究竟你正在尝试做一个更好的主意,但乍一看,这可能是它:

inputTypes-array设有两个Float.class-es,但你的方法使用原始类型。用大写字母Float不同于float小写字母,因此我期望有一个NoSuchMethodException

+0

好吧......那是对的哈哈。愚蠢的错误... –

0

您也可避免通过改变类如下声明输入参数类型,你可以做到这一点的构造函数外:

公共类运营商{

static final String ADD = "+"; 
static final String MULTIPLY = "*"; 
static final String SUBTRACT = "-"; 
static final String DIVIDE = "/"; 

private static Method[] methods; 
static Map<String, Method> methodsMap = new HashMap<String, Method>(); 
static { 

    methods = Operators.class.getMethods(); 
    try { 
     methodsMap.put(ADD, getMethod("add")); 
     methodsMap.put(MULTIPLY, getMethod("multiply")); 
     methodsMap.put(SUBTRACT, getMethod("subtract")); 
     methodsMap.put(DIVIDE, getMethod("divide")); 

    } catch (NoSuchMethodException e) { 
     // handle error 
     e.printStackTrace(); 
    } 
} 



static Method getMethod(String s) throws NoSuchMethodException { 

    for (Method method : methods) { 
     if (method.getName().equalsIgnoreCase(s)) 
      return method; 
    } 

    throw new NoSuchMethodException(s); 
} 

public static float add(float x, float y) { 
    return x + y; 
} 

public static float multiply(float x, float y) { 
    return x * y; 
} 

public static float subtract(float x, float y) { 
    return x - y; 
} 

public static float divide(float x, float y) { 
    return x/y; 
} 

}

和你可以使用方法图:

System.out.println(Operators.methodsMap.get("+").invoke(null, 1.0, 1.0));