java - GenericArrayType 接口(interface)的实例

标签 java reflection

class ReflectionClass{
   public static void anyMethod(Type type){
      if(type instanceof GenericArrayType){
         // some code
      }
   } 
}
class Client{
   public static void main(String[] args){
      anyMethod(...);
   }
}

我试图在 if(type instanceof GenericArrayType) 语句中接收“真”值。

那么,我应该将什么作为参数放入 Client 类中的 anyMethod 方法调用中?

来自关于 GenericArrayType interface 的 Oracle 文档:

GenericArrayType represents an array type whose component type is either a parameterized type or a type variable.

但是,我也知道我不能从 here 创建参数化类型的数组

那么,我该如何实现呢?

最佳答案

在属于通用数组类型的任何方法、字段等上使用反射。

例如,List.toArray(T[]) -> T[]

List.class.getMethod("toArray", Object[].class).getGenericReturnType();

或者自己声明一个泛型数组,反射(reflection)一下

public List<String>[] array;

MyClass.class.getField("array").getGenericType()

关于java - GenericArrayType 接口(interface)的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32206811/

相关文章:

Java ExecutorService 获取所有任务的反馈

java - 通过反射获取固定泛型参数的父方法

java - 如何通过反射修改列表

java - 检查父类(super class)/接口(interface)方法和重写方法是否相等

Java Reflection API - 获取 String[] 字段的值

java - 如何避免运行我的程序 10 次以获得 10 个答案?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?

java - 如何获取 Java 代理的调用处理程序?

java - 在循环中将局部变量声明为 final

java - SQLite where 子句