Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create objects of generic type with unknown in compilation type parameter

I have generic class :

class Field<T> { }

And some other class (whose type I know only at runtime) with many get methods for example :

   class A{
      public Date getDate();
      public String getName();
      public Integer getNumber();
   }

I want to create instances of class Field for all get methods, with T equals to return type of these get methods. For this example Field<Date>, Field<String>, Field<Integer>.

Can anybody help?

like image 529
user2410400 Avatar asked Oct 05 '22 01:10

user2410400


2 Answers

You use reflection typically for things that you only know at run-time. Generics information is erased at compile-time. So, while there are cases where you can mix the two, it is not common.

I want to create instances of class Field for all get methods, with T equals to return type of these get methods. For this example Field, Field, Field.

To answer your question literally:

Field<Date> dateField = new Field<Date>();
Field<String> nameField = new Field<String>();
Field<Integer> numberField = new Field<Integer>();
like image 131
ktm5124 Avatar answered Oct 13 '22 11:10

ktm5124


I don't believe you can create generic types of Field in this case, since generics are checked at compile time, while you are only able to get (via reflection) the return types of the declared methods of class A at runtime.

like image 37
nitegazer2003 Avatar answered Oct 13 '22 10:10

nitegazer2003