Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
    }
}

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.

Here's the stack trace:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
363 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Try this:

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

along with this:

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...