1

尝试在同一类中的方法上调用 getMethod 时遇到 NoSuchMethodException,而从哈希映射中提取的字符串名称没有参数。任何建议,或仅给出方法的字符串名称来调用同一类中的方法的另一种方法?获取方法的调用在这里:

if (testChoices.containsKey(K)) {
        String method = testChoices.get(K);
        System.out.println(method);

        try {
            java.lang.reflect.Method m = TST.getClass().getMethod(method);
            m.invoke(testChoices.getClass());
        } catch (NoSuchMethodException e1) {
            // TODO Auto-generated catch block
            System.out.println("No method found");
            e1.printStackTrace();
        } catch (SecurityException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();


        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

我试图调用的方法之一是这里:

private static void testgetDomainLic() throws IOException {

被调用的地图条目在这里:

testChoices.put(1, "testgetDomainLic");
4

2 回答 2

0

我不是专家,但请尝试更改您的方法,使其不是私人的。

私有方法可以通过反射调用,但有额外的步骤。请参阅任何方式调用私有方法?

于 2017-06-29T14:37:55.417 回答
0

我认为在您的情况下,您可以更改getMethodgetDeclaredMethod. getMethod只返回公共方法。

这里的问题是它们实际上具有不同的语义,不是它们是否返回非公共方法。getDeclaredMethod仅包括已声明但未继承的方法。

例如:

class Foo { protected void m() {} }
class Bar extends Foo {}
Foo actuallyBar = new Bar();
// This will throw NoSuchMethodException
// because m() is declared by Foo, not Bar:
actuallyBar.getClass().getDeclaredMethod("m");

在最坏的情况下,您必须遍历所有声明的方法,如下所示:

Class<?> c = obj.getClass();
do {
    for (Method m : c.getDeclaredMethods())
        if (isAMatch(m))
            return m;
} while ((c = c.getSuperclass()) != null);

或者考虑接口(主要是因为它们现在可以声明静态方法):

List<Class<?>> classes = new ArrayList<>();
for (Class<?> c = obj.getClass(); c != null; c = c.getSuperclass())
    classes.add(c);
Collections.addAll(classes, obj.getClass().getInterfaces());
Method m = classes.stream()
                  .map(Class::getDeclaredMethods)
                  .flatMap(Arrays::stream)
                  .filter(this::isAMatch)
                  .findFirst()
                  .orElse(null);

作为旁注,您可能不需要调用m.setAccessible(true),因为您是在声明它的类中调用它。但是,在其他情况下,这是必要的。

于 2017-06-29T15:10:20.880 回答