1
Test test1 = new Test();

here, new Test() means create new instance of class Test and assign it to reference test1.

Class<Test> test2 = Test.class;
Test test2Instance = test2.newInstance();

I am not able to define (in words) 1st statement. On the other hand 2nd statement it pretty clear to me.

EDIT

String is an instance of the class Class.

A string literal (e.g. "I am a string.") is an instance of the class String.

class literal (e.g. Hashtable.class) is an instance of the class Class.

Amit Yadav
  • 32,664
  • 6
  • 42
  • 57

3 Answers3

2
Class<Test> test2 = Test.class;

This statement declares a variable named test2, of type Class<Test>. It initializes this variable with the unique instance of this type, using the class literal expression Test.class which refers to the class Test.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • .@JB Nizet you included "class literal expression" in your answer give me clue and i googled it and come to a link http://stackoverflow.com/questions/2160788/what-is-a-class-literal-in-java and I got it what i am looking for. – Amit Yadav Jan 26 '15 at 16:15
  • 1
    `Test.class` is indeed a class literal. Just like `1` is an integer literal and `"hello"` is a String literal. – JB Nizet Jan 26 '15 at 16:17
1
Class<Test> test2 = Test.class;

means "give me the Class object representing the Test class and store it in the variable test2.

Aside from Class being generic, this has little to do with generics. It's about class objects.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
0

Class<Test> is a specific type of a generic type. Literally you are defining a variable test2 which is of type Class<T> with T == Test.

Class<T> is a parametric type, it depends on T, if you add the constraint T == Test then you are talking about a variable of Class<Test> (which is a specific different type).

It's orthogonal compared to polymorphism by subtype. If you have

class Base { .. }
class Derived extends Base { .. }

and you write

Derived derived = ...

You have no problems in stating that you are declaring a variable named derived of type Derived. This is the same thing, but Class<Test> is not a subtype of Class<T> but a specialization of it.

Jack
  • 131,802
  • 30
  • 241
  • 343