Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these 'generic' syntaxes in Java

Tags:

java

generics

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 am able to compile both - so I definitely did some basic checks here.

like image 982
Bi Act Avatar asked Nov 14 '15 19:11

Bi Act


2 Answers

  • In case of T clazz we expect an instance of a class,
  • In case of Class< T > clazz we expect an instance of Class which describes T (class literal).

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

  • In the first example, clazz will allow us to store 1, 2, etc.
  • But in the second example it will expect Integer.class.
like image 54
Pshemo Avatar answered Oct 13 '22 08:10

Pshemo


private T clazz;

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

In this case, the name says it is a class (clazz), but the value need to be Class object.


private Class< T > clazz;

Here, it is the Type of the Class. Class is a generic type, so here clazz can hold only Class object which Type is of Serializable.

like image 28
rajuGT Avatar answered Oct 13 '22 08:10

rajuGT