【问题标题】:type of parameter when using java reflection使用java反射时的参数类型
【发布时间】:2014-02-03 15:16:42
【问题描述】:

在库中,有一个函数以 Class 对象为参数:

public void libMethod(Class<?> cls){...}

我需要以 Java 反射的方式调用这个库函数。

例如我有一个班级:

public MySchool extends School{...}

我想将MySchool 类传递给库函数。我试过了:

//I can successfully get library class & a instance of it
Class<?> libClass = GET_LIB_CLASS();

//How can I define the type for the parameter?
Method m = libClass.getDeclaredMethod("libMethod", new Class[]{MySchool.class});
return m.invoke(libClass.newInstance(), MySchool.class);

上面的方法我试过了,还是不行。

如何在上面的java反射方式中定义参数的类型?

【问题讨论】:

    标签: java reflection


    【解决方案1】:

    请注意,您的方法采用Class&lt;?&gt; 类型的参数。您传递给Class#getDeclaredMethod() 的参数是该方法的格式参数类型的Class 实例数组,在本例中为Class.class,而不是MySchool.class

    所以,你应该得到这样的方法:

    Method m = libClass.getDeclaredMethod("libMethod", new Class[]{Class.class});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-25
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多