newbie
newbie

Reputation: 24635

Populating List items in Java via Reflection

I have to populate object with values that are in String format and I have converter to convert String values to whatever values are required. But how can I know type of List items? Is it List<String> or List<Integer>?

Upvotes: 1

Views: 1396

Answers (4)

Gursel Koca
Gursel Koca

Reputation: 21280

Java generics are compile time features, List<String> and List<Integer> are same at runtime.. Therefore you can not know component type of a Collection at runtime..

This kind of question asked so many times, there is a way to get component type of Collection at runtime, but you can extend a collection class, while constructing it, you can give component class to the constructor, by this way you can get component type of collection at runtime.. Here is a sample ;

class GenericList<T> extends ArrayList<T> {
private Class<T> componentClasz;

public GenericList(Class<T> clasz){
    super();
    componentClasz = clasz;
}

public Class<T> getComponentClasz() {
    return componentClasz;
}

}

GenericList<String> list = new GenericList<String>(String.class);

Upvotes: 2

Rich Hill
Rich Hill

Reputation: 463

You'd have to examine the object(s) of the list, not the list itself. Because Java uses type safe erasure and not reification there's no way to reflect the generic type of the list (or any other Java collection for that matter).

Upvotes: 0

tim_yates
tim_yates

Reputation: 171074

Depending on your use case, you can get the Generic type of a List via a few different methods.

This post shows how it can be done for return types of methods, parameters of methods, and field variables

When runtime inspecting a parameterizable type itself, like java.util.List, there is no way of knowing what type is has been parameterized to. This makes sense since the type can be parameterized to all kinds of types in the same application. But, when you inspect the method or field that declares the use of a parameterized type, you can see at runtime what type the paramerizable type was parameterized to.

If it's not one of these 3 cases, you cannot get the Generic type due to type erasure.

Upvotes: 2

Edwin Buck
Edwin Buck

Reputation: 70899

The type of the List was erased when the List was compiled.

Also, a String can't just be "converted" into any value willy-nilly. For example of a conversion failure, what's the appropriate Integer value for "hello"?

If you want a list that can hold any Java object, use List<Object>.

Upvotes: 1

Related Questions