【问题标题】:Identifying the class type for arguments required in gerDeclaredMethod in java识别 java 中 gerDeclaredMethod 所需参数的类类型
【发布时间】:2019-05-28 14:07:22
【问题描述】:

我正在使用 Java 反射来调用具有这 4 种参数类型的方法 xyz:

Set<LineItems> 
String
Document
Profiler

使用 getDeclaredMethod 时,我需要提供方法参数类型。如果String的参数类型是String.class,那么Set&lt;LineItems&gt;应该怎么做?应该是 Set.class 吗? (记住 Set 是一个接口)

函数 xyz 是接口 abc 中的默认函数。该接口正在多个其他类中实现,因此方法应仅在此处体现。这是我的代码:

Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Document.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;

我收到 NoSuchMethodFoundException 我知道这可能存在多个缺陷。有什么帮助吗?

【问题讨论】:

    标签: java class reflection


    【解决方案1】:

    Set&lt;LineItems&gt;?应该怎么做

    你在Set.class 那里应该做的事情。请记住,Java 泛型带有type erasure,因此,在运行时,该方法的签名也会显示Set.class

    是的,当您打算调用的方法的 签名 是 Set 时,那么使用 Set(接口)类正是您必须做的。例如,如果方法签名说HashSet,那么Set.class不会这样做!

    【讨论】:

      【解决方案2】:

      我能够通过以下方式解决这个问题:

      Object[] args= new Object[4];
      args[0]= setOfItems;
      args[1]= aString;
      args[2]= document;
      args[3]= profiler;
      
      Method m = this.getClass().getMethod("xyz", Set.class, String.class, Document.class, Profiler.class);
      Object result = proxy.invoke(m, this, args)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-26
        • 2011-06-02
        • 2020-01-11
        • 2018-07-26
        • 2012-03-05
        • 1970-01-01
        相关资源
        最近更新 更多