开发者

Java generic usage question

Say I want to do something like

public开发者_Go百科 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?


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.


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();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜