Reputation: 2424
Whenever I tried to use primitive type like boolean
with Class.forName()
syntax and with getClass()
, compile time error was generated, but when I used .class
syntax, it worked and the output was boolean
.
My question is why does it work with .class
syntax? I thought there should be always an object in place of String
in String.class
.
public class reflect2
{
public static void main(String[] args)
{
Class c1 = boolean.class;
System.out.println(c1.getName());
}
}
Upvotes: 1
Views: 1048
Reputation: 417572
The getClass()
is a method defined in java.lang.Object
, and methods can only be called on instances.
The .class
is part of the class literal, it is not a method call, and it is allowed on primitive types too.
Quoting from the The Java™ Language Specification Section 15.8.2. Class Literals:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type
void
, followed by a'.'
and the tokenclass
.
And finally qutoing from the javadoc of Class.forName()
:
Returns the Class object associated with the class or interface with the given string name.
So Class.forName()
only works for classes and interfaces and not for primitive types.
Upvotes: 2
Reputation: 393781
This is mentioned in the Oracle Java tutorials :
The .class Syntax
If the type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type. This is also the easiest way to obtain the Class for a primitive type.
boolean b;
Class c = b.getClass(); // compile-time error
Class c = boolean.class; // correctNote that the statement boolean.getClass() would produce a compile-time error because a boolean is a primitive type and cannot be dereferenced. The .class syntax returns the Class corresponding to the type boolean.
You need to be able to represent the type of primitives somehow, since it is required when, for example, you use reflection to search for methods or constructors that have primitive argument types.
Upvotes: 3