开发者

Java generic usage question

开发者 https://www.devze.com 2023-01-20 14:57 出处:网络
Say I want to do something like public开发者_Go百科 class Container<C extends Member> { public void foo() {

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

精彩评论

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

关注公众号