Using the getClass () Method

I tried to use the getClass () method and had the following code:

class parent{} class child extends parent{} public class test { public static void main(String[] args){ child b= new child(); System.out.println(b.getClass()==parent.class); } } 

I got a compilation error saying Incompatible operand types Class<capture#1-of ? extends child> and Class<parent> Incompatible operand types Class<capture#1-of ? extends child> and Class<parent> , and that’s fine if I initialize b with Object b= new child(); . Can someone tell me what is the difference between the two?

Thanks in advance.

+6
source share
3 answers

Since the advent of generics in Java 5, the java.lang.Class class has been common to the type it represents. This allows you to create an object through their Class without actuation and allows you to use other useful idioms.

This is why the compiler may become too smart and see that it is able to fully evaluate the expression at compile time: your expression is always false . The compiler gives you a type compatibility error, but this is a direct result of the fact that the expression is a compile-time constant.

One way to avoid this is to use java.lang.Object as a type. Once you do this, the compiler will no longer be able to accurately evaluate the result type of getType , thereby avoiding the error.

Another way to fix this problem is to cast the return type into a non-generic Class

 System.out.println(((Class)b.getClass())==parent.class); 

or using an intermediate variable of a non-general type:

 Class bClass = b.getClass(); System.out.println(bClass==parent.class); 
+6
source

This error message basically means that the compiler can tell when it compiles the program that the answer to this equality check will always be false. Since he knows that the child class and the parent class can never be equal, he refuses to compile the code.

+1
source

if you want to judge whether b.getClass () is an inheritance of parent.class, I suggest using this method:

  public static boolean judgeInherit(Class targetClass,Class supClass){ Class supperClass = targetClass; while(supperClass !=null){//if have supper class if(supperClass == supClass){ system.out.println(targetClass.getName() + " inherit "+supClass.getName()); return true; } supperClass = supperClass.getSupperclass(); } return false; } 

and call

 system.out.println(judgeInherit(b.getClass(),parent.class)); 
-1
source

Source: https://habr.com/ru/post/952473/


All Articles