在方法调用的时候,有时候需要传一个Class<T>泛型过来。

但是,有时候,传过来的Class又是泛型。

比如下面代码

List<User>

这时,传过去的只能是

List.class

此时就达不到我们想要的类型,List<User>的效果。

在这里只要实现一个类就可以获取到List<User>

public class DefaultTargetType<T> {

    private Type type;
    private Class<T> classType;

    @SuppressWarnings("unchecked")
    public DefaultTargetType() {
        Type superClass = getClass().getGenericSuperclass();
        this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
        if (this.type instanceof ParameterizedType) {
            this.classType = (Class<T>) ((ParameterizedType) this.type).getRawType();
        } else {
            this.classType = (Class<T>) this.type;
        }
    }
}

结果:

Class<List<User>> classType = new DefaultTargetType<List<User>>() {}.getClassType();

就可以获取到泛型中的类型了。

 

相关文章:

  • 2021-12-25
  • 2022-01-19
  • 2022-01-30
  • 2021-06-27
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-03-19
  • 2022-12-23
相关资源
相似解决方案