Consider this example (typical in OOP books):
I have an Animal
class, where each Animal
can have many friends.
And subclasses like
This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:
public void addFriend(String name, Class type, T animal);
public T callFriend(String name, Class type);
Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.