getDeclaredMethod不起作用,NoSuchMethodException [英] getDeclaredMethod doesn't work, NoSuchMethodException

查看:1973
本文介绍了getDeclaredMethod不起作用,NoSuchMethodException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在Java中使用 Reflection ,但它并不是很好。这是我的代码:

I've been trying to use Reflection in Java, but it doesn't end up pretty well. Here's my code:

public class ReflectionTest {
    public static void main(String[] args) {
        ReflectionTest test = new ReflectionTest();
        try {
            Method m = test.getClass().getDeclaredMethod("Test");
            m.invoke(test.getClass(), "Cool story bro");
        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.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();
        }
    }

    public void Test(String someawesometext) {
        System.out.println(someawesometext);
    }
}

我只是得到 java .lang.NoSuchMethodException 错误,我已经尝试了很多东西。
比如使用 getMethod 而不是 getDeclaredMethod ,添加 test.getClass()测试之后 getDeclaredMethod 等等。

I just get the java.lang.NoSuchMethodException error, and I've tried pretty much everything. Like using getMethod instead of getDeclaredMethod, add test.getClass() after "Test" in getDeclaredMethod and more.

这是堆栈跟踪:

java.lang.NoSuchMethodException: ReflectionTest.Test()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at ReflectionTest.main(ReflectionTest.java:10)

我一直在谷歌搜索很多天但没有运气。所以我知道我应该怎么解决这个问题?

I have been Googling for many days now but with no luck. So I does anyone know how I'm supposed to fix this?

推荐答案

你在中指定一个名字getDeclaredMethod 但没有参数,尽管 Test 方法的签名中有一个参数。

You specify a name in getDeclaredMethod but no parameter, although the Test method does have a parameter in its signature.

试试这个:

Method m = test.getClass().getDeclaredMethod("Test", String.class);

以及:

m.invoke(test, "Cool story bro");

因为Method.invoke 需要一个对象。但是在静态方法的情况下忽略此参数:

Because the first argument of Method.invoke expects an object. However this argument is ignored in case of static methods:


如果基础方法是静态的,那么指定的obj参数是
忽略。它可能为空。

If the underlying method is static, then the specified obj argument is ignored. It may be null.

这篇关于getDeclaredMethod不起作用,NoSuchMethodException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆