0

Possible Duplicate:
how to get class instance of generics type T

Template's T at

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

can not compile T.class , do it need reflection and how?

    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);
    }
Community
  • 1
  • 1
Martin Lee
  • 23
  • 2
  • 8

1 Answers1

3

Due to the way Java handles generic types, this code cannot work:

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

You need to pass the actual generic type to the constructor (or any other method):

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

The classic way is to infer the generic type from an array as an array does hold its type:

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

This is because the actual runtime type of Factory<T> is merely Factory, so the runtime has no access to its generic type.

John Dvorak
  • 26,799
  • 13
  • 69
  • 83