开发者

cannot instantinate generic type instance in Java [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Create instance of generic type in Java?

I've a little trouble. I cannot instantinate generic type instance in default constructor. here is my class

public class MyClass<U extends MyUser> {
    private U user;

    public U getUser() {
        return this.user;
    }

    public void setUser(U user) {
        this.user = user;
  开发者_如何学C  }

    public MyClass() {
        this.user = new U();
    }
}

in code line this.user = new U() I'm getting exception

cannot instantinate type U

. How can I create new instance of U?

Thanks in advance


You need to specify a type when instantiating your User. That type needs to be a MyUser or subtype of MyUser.

public class MyClass<U extends MyUser>{
private U user;
public U getUser(){
return this.user;
}

public void setUser(U user){
  this.user=user;
}

public MyClass() {
    this.user=new MyClass<U>();
  }
}


Java generics do not know the types of their templated parameters at runtime. Therefore, in your example, the runtime type of U is not known, so the constructor cannot execute new U().

You will need to pass in the type of U (something like Foo.class) to the conctructor in order for it to know how to create a new obejct of type U.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜