1

Possible Duplicate:
Get generic type of java.util.List

How can I see what type is within a list in a parameter

private List<String> names;

how would I be able to find out that its a list of Strings? My goal is to make a method like this working:

public Field findFieldByObjectType(Class<?> clazz, Object obj) {
    for (Field field : clazz.getDeclaredFields()) {
        // if field type is List<obj>
        // return field
    }
}
Community
  • 1
  • 1
Moose Moose
  • 267
  • 5
  • 13
  • 1
    This OS question should give you some clues: http://stackoverflow.com/q/3403909/1916110 – Tom Jan 13 '13 at 17:48
  • Do you want the static type (as declared) or the type of the elements in a specific instance? – Henry Jan 13 '13 at 17:49
  • 2
    This is the closest thing you can achieve http://stackoverflow.com/a/1942680/1317692 – Fallup Jan 13 '13 at 17:50

2 Answers2

1

You can either use instanceof operator or the getClass() method on the element(s) of the list.

private List<String> names;

becomes

private List names;

after type erasure.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
  • 1
    But how can I do getClass() on the elements? The list isnt even initialized – Moose Moose Jan 13 '13 at 17:48
  • The getClass() works at runtime by when you should have it initilized. – Bhesh Gurung Jan 13 '13 at 17:51
  • @MooseMoose you cannot, since `.getClass()` is a runtime operation, and the generic type is erased at runtime (this is called type erasure). IOW, there is no such thing as `List.class`, at runtime, it becomes `List.class`. – fge Jan 13 '13 at 17:51
  • No since I'm only getting the fields from the Class>, it will never be initialized – Moose Moose Jan 13 '13 at 17:52
  • 2
    thats not true, when I'm printing field.getGenericType() it gives me java.util.List – Moose Moose Jan 13 '13 at 17:59
1

As I said in comments, this is the closest thing what you can achieve with the help of reflection https://stackoverflow.com/a/1942680/1317692. Credit goes to BalusC.

Community
  • 1
  • 1
Fallup
  • 2,417
  • 19
  • 30