The difference between these generic syntaxes in Java

Consider this:

public abstract class AbstractHibernateDao< T extends Serializable > { private T clazz; } 

And this:

 public abstract class AbstractHibernateDao< T extends Serializable > { private Class< T > clazz; } 

I can compile both - so I definitely did some basic checks here.

+5
source share
4 answers
 private T clazz; 

Here, clazz can contain any type that is of type Serializable, even your custom class object, if it is of type Serializable.

In this case, the name says that it is a class ( clazz ), but the value must be an object of the class.


 private Class< T > clazz; 

Here it is a Type Class . Class is a generic type, so here clazz can only contain a class object that is of type Serializable.

+4
source
  • In the case of T clazz we expect an instance of the class,
  • In the case of Class< T > clazz we expect an instance of Class that describes T (class literal).

So, let's say that as T we will use Integer . In this case:

  • In the first example, clazz will allow us to store 1 , 2 , etc.
  • But in the second example, it expects Integer.class .
+11
source

The first creates a clazz variable of type T.

The second creates a clazz variable of type Class, which is a typical type and parameterized by T. Comparison with the list <T>, that is, the list T.

+3
source

In the first you get an instance of T, and in the second you get an instance of class T (basically what you get from calling clazz.getClass() in the first case).

+3
source

Source: https://habr.com/ru/post/1235962/


All Articles