Generic method in Java without generic argument

前端 未结 5 2076
无人共我
无人共我 2020-12-02 13:32

In C# I can do actually this:

//This is C#
static T SomeMethod() where T:new()
{
  Console.WriteLine(\"Typeof T: \"+typeof(T));
  return new T();
}
         


        
5条回答
  •  情歌与酒
    2020-12-02 14:08

    In Java, generics are compile-time only data, which are lost at run time. So, if you called a method like that, the JVM would have no way of knowing what T.class was. The normal way to get around this is to pass a class instance object as a parameter to the method, like this:

    public static  T fromXml(Class clazz, String xml) {
      try {
        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller um = context.createUnmarshaller();
        return (T)um.unmarshal(new StringReader(xml));
      } catch (JAXBException je) {
        throw new RuntimeException("Error interpreting XML response", je);
      }
    }
    
    fromXml(SomeSubObject.class, "");
    

提交回复
热议问题