0

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;
    }

    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

Community
  • 1
  • 1
pofighist
  • 1
  • 1

2 Answers2

0

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>();
  }
}
Joeblackdev
  • 6,967
  • 23
  • 64
  • 103
0

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.

David R Tribble
  • 10,646
  • 4
  • 39
  • 50