Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use generic type as class

 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello!


I would like to be able to instantiate the class, without the needing to pass a parameter. I think that maybe it is possible, because T represent this class.
Something like this:

Is there a way to do this?
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Hibernate Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Leandro
Please give details so that we understand your question.
I have seen your code but code will not compile.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you cannot do that the way you proposed. Generics in Java have certain limitations, one of them is that you can't instantiate an object from a generic type with for example "new T()". Probably that's the reason why your class needs the Class parameter - so that it can create new instances of that class with: persistentClass.newInstance().

If you want to know all the details of Java generics and why "new T()" doesn't work, see Angelika Langer's Java Generics FAQ.

(The reason why new T() doesn't work is because of type erasure - see this from that FAQ for more info).
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!

Great link.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic