Mushy
Mushy

Reputation: 2645

Java Reflection getDeclaredMethod(...) Returning Null

I have imported the fully qualified name of the class and created an instance of the class. I then proceeded to acquire the private method name of the class:

InvokeCallWebservice invokeCallWebservice = new InvokeCallWebservice();

Method method = null;

try {
     method = invokeCallWebservice.getClass().getDeclaredMethod("Fully Qualified Class Name.getURL", String.class);
} 
catch (SecurityException e) {
     System.out.println(e.getCause());
} 
catch (NoSuchMethodException e) {
     System.out.println(e.getCause());
}

    System.out.println(method.getName());

An exception is thrown because method is null. I am not sure the reason which could be the class exists in a different project and package or because I need to specify the second argument as many times as there are parameters in the method. Can I actually invoke this on a private method?

Here is the stack trace:

java.lang.NoSuchMethodException: InvokeCallWebservice.getURL(java.lang.String)
at java.lang.Class.getDeclaredMethod(Class.java:1937)
at com.geico.debug.Debug.main(Debug.java:39)

Upvotes: 0

Views: 3044

Answers (3)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

The Class#getDeclaredMethod(String, Object...) method javadoc states

The name parameter is a String that specifies the simple name of the desired method

The simple name being just the name of the method as it appears in the source code, not qualified with the class it belongs to.

getDeclaredMethod() will throw a NoSuchMethodException if no such (named) method exists. In your case, you just print the cause, but still try to use the method variable even if it wasn't assigned. So it remains null and you get a NPE.


If your method takes 5 String arguments, then you need to use

getDeclaredMethod("getURL", String.class, String.class, String.class, String.class, String.class);

to match all its parameter types.

Upvotes: 2

Shreyos Adikari
Shreyos Adikari

Reputation: 12744

The correct syntax is:

Method method = ClassName.getClass().getDeclaredMethod(methodName, methodParameters);

Here methodName is the name of the method and methodParameters is the the parameter array. Change it to:

method = invokeCallWebservice.getClass().getDeclaredMethod("methodName", String.class);

Where methodName is your method name.

For more details please read this doc.

Upvotes: 1

Garis M Suero
Garis M Suero

Reputation: 8170

You have to get the class first, and with that class, get the method you want to get, only using the method name and parameters.

Class clazz = Class.forName("package.ClassIWant");

Method myMethod = clazz.getDeclaredMethod("getURL", String.class);

Upvotes: 2

Related Questions