Implementing a Generics Based Java Factory Method

Beyond adding a type to a Collection, I still need a reminder about how to do more complicated things with generics! So, primarily for my own reference, here is an example of implementing a generics-based Java factory method.

public abstract class PrintingDelegate {
   public static PrintingDelegate getInstance(
         final Class<? extends PrintingDelegate> delegateClass) {
      try {
         return delegateClass.newInstance();
      } catch (Exception e) {
         throw new IllegalArgumentException(e);
      }
   }
}
public final class PrintingDelegateXxx extends PrintingDelegate { ... }
public final class PrintingDelegateYyy extends PrintingDelegate { ... }

I got this from Roland Illig's answer to this StackOverflow post: Am I implementing a generics-based Java factory correctly?

Popular Posts