tags:

views:

46

answers:

2

Say I want to do something like

public class Container<C extends Member> {

    public void foo() {
        C newC = new C();
    }
}

I realize that this will not work, but what is the correct Java idiom for this?

+1  A: 

The typical idiom is indroducing a type tag passed in constructor:

public class Container<C extends Member> {
    private Class<C> tag;

    public Container(Class<C> tag) {
        this.tag = tag;
    }

    public void foo() {
        C newC = tag.newInstance();
    }
}
axtavt
+2  A: 

The generic type C is erased at runtime to java.lang.Object. There is no way of instantiating an erased generic type. It seems more like you want some sort of factory creational pattern?

abstract class MemberFactory {
   public static <T> Member create(Class<T> memberClass) throws Exception {
      return memberClass.newInstance();
   }
}

Member premiumMember = MemberFactory.create(PremiumMember.class);

If this is the case, you might want to look at using dependency injection and frameworks like Spring, or Guice.

hisdrewness