Using generics as comments.

Overview

Usually generic types are one letter which are left to the imagination as to what they stand for. However Generics can be used in other ways to make coding clearer.

Typed by conversion.

Some types are purely based on convention. e.g. POJO, JavaBean, Array. These types are typically declared as Object which could be anything. Java has no way to describe these meta-classes at compile time. However their types can be documented as generics.

public <Pojo> void printAsKeyValues(Pojo object);

public <JavaBean, T> T getValue(JavaBean bean, String fieldName, Class<T> expectedClass);

// todo int[] extends Object not Object[].
public <Array> int getLength(Array object);

Functional methods which return the same type.

Generics can be useful for stating that a return type is the same as one of the arguments.

public <E, C extends Collection<? extends E>> C functionalAdd(C collection, E element);

This states that the method return the same type as the first argument. Give it a Set<String> and it returns a Set<String>, give it a BlockingQueue<Thread> and it returns the same.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. May 10, 2008

    Anonymous says:

    你太有才了!! it's a pop words current in  China. to English, maybe like this: ...

    你太有才了!!

    it's a pop words current in  China. to English,

    maybe like this:

    U 2 talented!!

    (I not know its color of feel.)

  2. May 10, 2008

    Anonymous says:

    Sometime I do some comments in code by using log. log.debug("It's should a pojo...

    Sometime I do some comments in code by using log.

    log.debug("It's should a pojo");

Add Comment