Why ReflectionChild.class.isInstance(Class.class) is not true?
As we know in reflection Class.class.isInstance(Class.class) is true. Now see on below code snip.
ReflectionChild ch = new ReflectionChild(); //Take random class
if(ch.getClass()==ReflectionChild.class){
System.out.println("ch.getClass()==ReflectionChild.class");
}
System.out.println(ReflectionChild.class.getClass());
System.out.println(Class.class);
if(ReflectionChild.class.getClass()==Class.class){
System.out.println("ReflectionChild.class.getClass()==Class.class");
//System.exit(0);
}
if(ReflectionChild.class.isInstance(Class.class)){
System.out.println("true");
//System.exit(0);
}else{
System.out.println("false");
}
The output is :-
ch.getClass()==ReflectionChild.class // 1st SYSOUT
class java.lang.Class // 2nd SYSOUT
class java.lang.Class // 3rd SYSOUT
ReflectionChild.class.getClass()==Class.class //4th SYSOUT
false // 5th SYSOUT
According to above 1st four SYSOUT's the line ReflectionChild.class.isInstance(Class.class)
should be true. But for me it is false as output .
Can any one explain?
Class.class
is an instance of Class
, not ReflectionChild
.
Therefore, isInstance()
returns false.
Because a Class
instance is not an instance of of type ReflectionChild
.
From the javadoc
Specifically, if this
Class
object represents a declared class, this method returnstrue
if the specifiedObject
argument is an instance of the represented class (or of any of its subclasses); it returnsfalse
otherwise.
The argument you've provided is of type Class
which is not an instance of the type ReflectionChild
represented by the Class
instance returned by the class literal expression ReflectionChild.class
.
From the Javadocs of Class#isInstance(Object)
:
Determines if the specified
Object
is assignment-compatible with the object represented by thisClass
. This method is the dynamic equivalent of the Java language instanceof operator. The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by thisClass
object without raising aClassCastException
. It returns false otherwise.
So the object passed as an argument to the method must be an instance of the class represented by the object on which the method is called, not the other way around : the expression that should return true
is the following:
if(Class.class.isInstance(ReflectionChild.class)){
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.