I am trying to invoke a private method belonging to one class from another class using java reflection. Both these classes belong to different packages. Code sample is as below. But everytime I run the getDeclaredMethod it returns with NoSuchMethodException. How do I invoke the getCacheKey method from my class?
Thanks,
Class A
package com.abc;
public class TicketHelper
{
static String getCacheKey(String ticketString, Ticket ticket) throws TicketException, UnsupportedEncodingException, NoSuchAlgorithmException {
...
}
}
Class B
package com.def;
...
private Method method = null;
public class TicketHelper
{
...
try {
method = TicketHelper.class.getDeclaredMethod("getCacheKey", new Class[] {String.class, Ticket.class});
} catch (SecurityException e1) {
setTrace("Security exception2 " + e1.getMessage());
} catch (NoSuchMethodException e1) {
setTrace("No such method exception2 " + e1.getMessage());
}
method.setAccessible(true);
m_cacheKey = method.invoke(null, new Object[] {ticketString, ticket});
}
Is the class in com.def also called TicketHelper? In that case you need to qualify as
com.abc.TicketHelperEDIT
There are several compilation errors in the code you posted. Always try to come up with a short example that reproduces the problem; in most cases you will see you error in that process. The following works for me. It is same package, but that should not matter: