【问题标题】:Using generic type as class argument使用泛型类型作为类参数
【发布时间】:2016-02-11 01:25:22
【问题描述】:

我有这门课

class X<T>{
    public T dowhatever(){
         //jackson parsing
         ObjectMapper mapper = new ObjectMapper();
         T obj = mapper.readValue(jsonString, T);
         return obj;
    }
}

但显然,我不能将T 传递给 readValue 方法。我需要class 信息。有没有办法在不将Class 对象作为参数传递的情况下对其进行概括?

附注: 我省略了不必要的代码并留下了相关的内容。

【问题讨论】:

标签: java json generics jackson


【解决方案1】:

泛化它的唯一方法是通过一个特定类作为泛型的子类

class MyX extends X<Type> {

您可以在运行时获取Type,因为它必须可供编译器检查。

【讨论】:

    【解决方案2】:

    试试这个

    class X<T> {
        @SuppressWarnings("unchecked")
        public void dowhatever(T... dummy){
            Class<T> classT = (Class<T>)dummy.getClass().getComponentType();
            System.out.println(classT);
        }
    }
    
    class Person { }
    

    X<Person> x = new X<>();
    x.dowhatever(/* no arguments */); // -> class Person 
    

    或者你可以在构造函数中获取类对象。

    class X<T> {
    
        private final Class<T> classT;
    
        @SuppressWarnings("unchecked")
        public X(T... dummy) {
            classT = (Class<T>)dummy.getClass().getComponentType();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多