简体   繁体   中英

Generic and dynamically associated type

Probably, what I will ask is a terrible question, as the JAVA is strong-type language, but I will ask it, to be sure.

I wanted to implement few models, to which jackson will map to. Let's say that we have a: SomeObject which have a property value. SomeObject is an interface:

interface SomeObject <T> {
    T getValue();
}

Value can be a Boolean, can be a List, or can be a simple string. ObjectOne and ObjectTwo implements SomeObject I'm wondering, if we will have such object:

List<SomeObject> someObject = new ArrayList<>();

And we will have in that list: ObjectOne, ObjectTwo if there is a possibility to call getValue on each of those object, and without casting it to given class, get the proper value? I know I can do something like that:

(String) list.get(0).getValue();

but is there a way to get such results:

String firstItemIsAString = list.get(0).getValue();
ArrayList secondItemIsAnArrayList = list.get(1).getValue();

I know that this is not a javascript, but maybe with some help of Generics this may be achivable? I will add that item in the list of SomeObjects will be added in such way:

List<SomeObject> list = new ArrayList<>();
list.add(new ObjectOne<String>());
list.add(new ObjectTwo<ArrayList>());

As soon as you put a Boolean and an ArrayList together into some Collection, the generic type of the Collection will have to be some common type of both, which just leaves Object - thus you have no information about the types in the collection at all.

To answer your question directly: no, there is no way of saving the type of something within generics as those are gone during runtime.

Perhaps a helper method would help you pretend Java was less type safe:

public interface SomeObject <T> {
    T getValue();
}
public static void main(String...args){
    List<SomeObject<?>> objectList=new ArrayList<SomeObject<?>>();
    String firstItemIsAString = converter(objectList.get(0).getValue());
}
public static <t> t converter(Object input){
    return (t) input;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM