• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Generics: what is the difference between Class<T> and T?

 
Elia Bolg
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the following code was auto generated by Netbeans 7.3:

the abstract class:



extending the absrtact class:


why the following is not equivalent?:

my modified abstract class:
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your first example, entityClass is of type Class<T>, while in your second example, it is of type T.

Obviously, Class<T> and T are not the same type, so the examples are not equivalent. Why would you expect these to be equivalent?
 
Elia Bolg
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was under the impression that when you extend the abstract class, you provide the type T (Config as in my example) so in turn the entityClass would be : private Config entityClass; I'm not getting the Class<T> in this case.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Elia Bolg wrote:I was under the impression that when you extend the abstract class, you provide the type T (Config as in my example)


That's one way to do it, yes.

so in turn the entityClass would be : private Config entityClass; I'm not getting the Class<T> in this case.


Forget about extending. And mostly forget about generics for a minute. Just think about what Class<T> vs. T means.

Class<T> means java.lang.Class, where the Class object is the one representing the class T. It might be Class<String> for the String class, or class<com.mypackage.MyFooBar> for the MyFooBar class. But it's always java.lang.class.

T, on the other hand, is whatever class you want it to be. It might be String, or it might be comp.mypakcage.MyFooBar.

Now consider what you can do with a Class object vs. what you can do with a String or MyFooBar object. Consider what the difference is between have a variable Class x; and [b]MyFooBar x;[/t]

As to why that class is using Class<T> rather than just T, you'd have to look at the rest of the class and see how it uses that variable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic