Why should I care that Java doesn't have reified generics?

后端 未结 13 832
予麋鹿
予麋鹿 2020-11-28 02:59

This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It\'s commonly-identified as a pain that Jav

13条回答
  •  伪装坚强ぢ
    2020-11-28 03:12

    Type safety comes to mind. Downcasting to a parametrized type will always be unsafe without reified generics:

    List myFriends = new ArrayList();
    myFriends.add("Alice");
    getSession().put("friends", myFriends);
    // later, elsewhere
    List myFriends = (List) getSession().get("friends");
    myFriends.add(new Friend("Bob")); // works like a charm!
    // and so...
    List myFriends = (List) getSession().get("friends");
    for (String friend : myFriends) print(friend); // ClassCastException, wtf!? 
    

    Also, abstractions would leak less - at least the ones which may be interested in runtime information about their type parameters. Today, if you need any kind of runtime information about the type of one of the generic parameters you have to pass its Class along as well. That way, your external interface depends on your implementation (whether you use RTTI about your parameters or not).

提交回复
热议问题