2

我创建了一个哈希表,它将作为键保存一个字符串,该字符串将表示用户将提供的方法的名称,并将实际方法调用的值作为字符串也作为字符串。我正在使用的代码是这里的代码:

public void getMethod(String givenMethod){

    Map<String, String> methods = new HashMap<String, String>();
    methods.put("length", "length();");

    methods.get(givenMethod);

}

从主方法我调用 objectX.getMethod("length");,但方法​​ length(); 不执行。有人能帮助我吗?

4

3 回答 3

3

You are getting the method but you are not invoking it. You'll have to do something like this:

Method yourMethod = objectX.getClass().getDeclaredMethod("yourMethodName"); //This is the string that represents the name of the method.

Then you invoke the method. All this through reflection:

yourMethod.invoke(YourObject);

The parameter of the invoke method is first the object, and then the attributes.

You can also get the return type of the method and cast the result, since the invoking the method will result in an Object type method:

yourMethod.getReturnType(); //This line gives you the type returned by your method.
于 2012-05-10T20:05:24.270 回答
2

使用 Java **reflection 按名称调用方法
(如您所说,您将方法名称存储在地图中)。
有关更多详细信息,请阅读以下文章:http: //java.sun.com/developer/technicalArticles/ALT/Reflection/

于 2012-05-10T20:25:55.470 回答
1

您需要使用反射按名称调用方法。所以你的数据结构看起来更像

Map<String, Method> meth = new Hashmap<String,Method>();

其中Method是一个实际的对象。

于 2012-05-10T20:02:47.937 回答