繁体   English   中英

使用Java反射

[英]Using java reflection

我试图使用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 {}

不是解决方案,而是确定问题的测试:获取所有声明的方法并验证getCacheKey是否可见/存在:

Method[] methods = TicketHelper.class.getDeclaredMethods();
for (Method method:methods) {
  if (method.getName().equals("getCacheKey")) {
    System.out.println(method);  // <-- breakpoint and inspect the method object
  }
}

请查看: http//www.wikijava.org/wiki/Class_and_static_Method_Reflection_example

他们使用getMethod而不是getDeclaredMethod

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM