1

How to create class of T?

I need to bind from some Windows Communication Foundation (WCF) XML of the object T.

I can do this without errors:

ArrayList<T> list = new ArrayList<T>();

This is my function:

public static <T> ArrayList<T> GetListFromXml(String url,String element)

How to get: T obj = ?

javaPlease42
  • 4,263
  • 6
  • 33
  • 62
roy.d
  • 1,001
  • 2
  • 15
  • 33
  • Did you work through the [Java Generics tutorial](http://docs.oracle.com/javase/tutorial/java/generics/)? –  Mar 02 '12 at 09:18

1 Answers1

3

That is not possible due to the type erasure of the compiler. If you have a concrete type with a default constructor on caller side, the following may work:

public static <T> ArrayList<T> GetListFromXml(String url,String element, Class<? extends T> type) {
  T obj = type.newInstance();
  ...
}

If you need to pass parameters to the constructor, you have to get it from the class by getConstructor(parameter type 1, ...) (you need to handle the Exceptions not shown here):

MyParamType1 param1 = ...;
MyParamType2 param2 = ...;
Constructor<T> cons = type.getConstructor(MyParamType1.class, MyParamType2.class);
T obj = const.newInstance(param1, param2);
Arne Burmeister
  • 19,345
  • 8
  • 53
  • 90