我试图使用java反射从另一个类调用属于一个类的私有方法。这两个类都属于不同的包。代码示例如下。但是每次我运行getDeclaredMethod时,它都会返回NoSuchMethodException。如何从类中调用getCacheKey方法?
谢谢,
A级
package com.abc;
public class TicketHelper
{
static String getCacheKey(String ticketString, Ticket ticket) throws TicketException, UnsupportedEncodingException, NoSuchAlgorithmException {
...
}
}
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});
}
最佳答案
com.def中的类也称为TicketHelper吗?在这种情况下,您需要符合com.abc.TicketHelper
编辑
您发布的代码中存在几个编译错误。总是尝试提出一个简短的例子来重现该问题。在大多数情况下,您会在该过程中看到错误。以下对我有用。它是相同的程序包,但这无关紧要:
public class TicketHelperUser
{
public static void main(String[] args) throws Exception
{
for (java.lang.reflect.Method m : TicketHelper.class.getDeclaredMethods())
{
System.out.println(m);
}
java.lang.reflect.Method method = TicketHelper.class.getDeclaredMethod("getCacheKey", String.class, Ticket.class);
method.setAccessible(true);
method.invoke(null, new Object[] {"", new Ticket()});
}
}
public class TicketHelper
{
static String getCacheKey(String ticketString, Ticket ticket)
{
return "cacheKey";
}
}
public class Ticket {}