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,699
  • 7
  • 36
  • 65
roy.d
  • 1,030
  • 2
  • 16
  • 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
  • 20,046
  • 8
  • 53
  • 94
  • `ArrayList ycList = GetListFromXml(url, element, YourClass.class);`. [Class literals](http://stackoverflow.com/questions/2160788/what-is-a-class-literal-in-java). – lxbndr Mar 01 '12 at 15:30
  • can i send prameters to the constractor? – roy.d Mar 01 '12 at 15:44
  • @user1194088 You can send the type as a parameter to a class which takes a parameter e.g. if you write one. ArrayList doesn't take a type. – Peter Lawrey Mar 01 '12 at 15:47
  • i meant sent prameters to the T constractor, – roy.d Mar 04 '12 at 06:51