Java Generics an Google Juice Tricks

Since Java-5 generics are supported. Sadly, there’s no way to find out/specify the parameters at runtime. Normally you can life without this, but in the case of the dependency-injection libraries, this can get difficult.

Either you “ignore” the parameterization or you find a hack to deal with it. Ignoring works often, but sometime you really want a specific implementation which depends on the parameters:

public class DemoOne{
// A string-list constructor.
public DemoOne(List<String> strings){){/*constructor*/}
}public class DemoTwo{// A user-list constructor. If it is a user-list, I want a super-special-implementation injected.
public DemoTwo(List<User> users){/*constructor*/}

A List with strings may have complete other needs than a list with users. The “User”-list is maybe a list which loads users from the database whereas the other is just an array. Of course, the list-example is a bit stupid, in a real project this is more complex.

So  “List<User>” and the “List<String>” shouldn’t be a the same. But how request/specify a parameterized class? You can’t give a parameterized “Class”-instance as parameter to a method. Google Guice has a simple trick to handle it. The create an anonymous inner class, which extends a generic type. By doing this, they can read out the type via Reflection:

binder.bind(new TypeLiteral<List<String>>(){}).to(ArrayList.class);
binder.bind(new TypeLiteral<List<User>>(){}).to(LinkedList.class);

In my opinion, this is a really simple and smart trick.

Leave a Reply

Your email address will not be published. Required fields are marked *