Search code examples
javajava-8java-7java-6

What is difference between Myclass.class vs new MyClass()?


Team, While learning java (specially generics), i could see two different parameter in the method (.class and object reference) . When to use .class option and new myclass()? give me some example to understand


Solution

  • new MyClass(): will create an instance/object of type MyClass

    MyClass.class: is a "class literal" - a simple way of getting the Class for a particular type. in order to extract the metadata about the class such as fields and methods.

    Refer to the Java Language Specification for more details. (15.8.2 Class Literals)