如何在java中编写T.class?

时间:2012-10-26 08:36:23

标签: java

  

可能重复:
  how to get class instance of generics type T

模板的T 在

JAXBContext jaxbContext = JAXBContext.newInstance(T.class);

无法编译T.class,需要反思吗?

    public void ConvertObjectToXML(String path, T bobject)
    {
        //Convert XML to Object
        File file = new File(path);
        JAXBContext jaxbContext = JAXBContext.newInstance(T.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        T customer2 = (T) jaxbUnmarshaller.unmarshal(file);
        System.out.println(customer2);
    }

1 个答案:

答案 0 :(得分:2)

由于Java处理泛型类型的方式,此代码无法工作:

public class Factory<T>{
   public T create(){
      return T.class.newInstance();
   }
}

您需要将实际泛型类型传递给构造函数(或任何其他方法):

public class Factory<T>
   Class<T> c;
   publict Factory(Class<T> c){
       this.c=c;
   }
   public T create(){
       return c.newInstance();
   }
}

经典的方法是从数组推断泛型类型,因为数组确实保持其类型:

public interface List<T>{
   ...
   T[] toArray(T[] target);
   ..
}

这是因为Factory<T>的实际运行时类型仅为Factory,因此运行时无法访问其泛型类型。