Question

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?

Était-ce utile?

La solution

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>();

Autres conseils

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.

To obtain the getters, consider using introspection rather than reflection : it is intended for this purpose!

Here is a code to automatically obtain the getters. Beware, you also get "getClass()" getter!

for(PropertyDescriptor descriptor :Introspector.getBeanInfo(A.class).getPropertyDescriptors()){
  System.out.println("Getter method :" + descriptor.getReadMethod());
  System.out.println("Return type : " + descriptor.getReadMethod().getReturnType());
  Class<?> c=descriptor.getReadMethod().getReturnType();
}

}

Output :

Getter method :public final native java.lang.Class java.lang.Object.getClass()
Return type : class java.lang.Class
Getter method :public java.util.Date A.getDate()
Return type : class java.util.Date
Getter method :public java.lang.String A.getName()
Return type : class java.lang.String
Getter method :public java.lang.Integer A.getNumber()
Return type : class java.lang.Integer

Then, you can easily create a Field for each of those getters. For the generic type, it does not really make sense at runtime but it is still possible to use this in a code generator...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top