java - 查找方法参数类型或参数泛型类型

标签 java generics

我需要查找我当前的类是否有带有参数的方法,该参数的类型是 Integer,其泛型类型是 Integer。

我在main中写了以下内容:

public static main(String[] args){
   Class<?> clazz = Class.forName("Test");
   Class<?> lookingForClass = Integer.class;
   Method[] method = clazz.getMethods();
   for (int i = 0; i < method.length; i++) {
       Type[] types = method[i].getGenericParameterTypes();
       for (int j = 0; j < types.length; j++) {
           Type type = types[j];
           Class<?> result = type.getClass();
           if (type instanceof ParameterizedType) {
               ParameterizedType pt = (ParameterizedType) type;
               Type[] fieldArgTypes = pt.getActualTypeArguments();
               result = (Class<?>) fieldArgTypes[0];
           }
           if (result instanceof lookingForClass)
               System.out.println("found it");
           }
      }
}

public static void findTowInArray(List<Integer> A) {

}

public static void findTowInArray(Integer A) {

}

public static void findTowInArray(String A) {

}

但是我在 if (result instanceoflookingForClass)

上遇到编译错误
Incompatible conditional operand types Class<capture#6-of ?> and lookingForClass

出了什么问题?

最佳答案

如果 Type 已经是类,则不要对其调用 getClass()。

public static void main(String[] args) throws ClassNotFoundException{
    Class<?> clazz = Class.forName("Test");
    Class<?> lookingForClass = Integer.class;
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        Type[] types = method.getGenericParameterTypes();
        for (int j = 0; j < types.length; j++) {
            Type type = types[j];
            Class<?> result = type instanceof Class<?> ? (Class<?>)type : type.getClass();
            if (type instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) type;
                Type[] fieldArgTypes = pt.getActualTypeArguments();
                result = (Class<?>) fieldArgTypes[0];
            }
            if (result.equals(lookingForClass))
                System.out.println("found " + method);
            }
       }
 }

我更喜欢像这样的循环

for (final Method method : methods) {
    ...
}

如果您不需要索引。

关于java - 查找方法参数类型或参数泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17021780/

相关文章:

java - Struts2 JSP中获取请求头

c# - 通过 MVVM Light RelayCommand 绑定(bind)泛型类型

java - 如何引用 Java 中接口(interface)实现的类类型?

java - 基于 Spring 的 Web 应用程序中的分块 HTTP 响应

java - 在 Spring Batch 3.0.x 中 - 如何为非标准数据库设置数据库类型?

C# 反射,将 MakeGenericMethod 与具有 'new()' 类型约束的方法一起使用

generics - 如何在 swift 中编写通用工厂方法?

java - 在 eclipse 中构建项目,但不是从终端/jenkins - 使用 Ant

java - 从 String 到 java.security.PublicKey 对象给了我一个非法字符

java - AtomikosSQL异常 : Transaction is marked for rollback only or has timed out