my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes use generic type as class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "use generic type as class" Watch "use generic type as class" New topic
Author

use generic type as class

Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
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

Joined: Aug 31, 2007
Posts: 787

Leandro
Please give details so that we understand your question.
I have seen your code but code will not compile.


SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Thank you!

Great link.
 
 
subject: use generic type as class
 
Similar Threads
Spring Struts & Hibernate
Abstract Generic Class for DAO with spring SessionFactory injection setup help needed.
what is convenience method in java?
java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
Session is closed