.class == getClass () cannot validate

Here is a little code that I wrote to test (is this called a reflection API?), But while I am not getting the expected results. Here is the code:

public class Outer { public Outer(){ System.out.println("Outer Class"); } public class Inner { public Inner(){ System.out.println("Inner Class"); } } } 

Also here is the main function that I wrote to run the code and test it ...

 public class ClassTest { public static void main(String[] args) { Outer outObj = new Outer(); Outer.Inner inObj = outObj.new Inner(); // Using Reflection Class objTyp = inObj.getClass(); System.out.println(objTyp.getName()); //Testing Reflection if(objTyp.getClass() == Outer.Inner.class){ System.out.println("Match classes!"); }else{ System.out.println("Mismatch classes!"); } } } 

The test fails with the following error:

if (objTyp.getClass () == Outer.Inner.class) {^ where CAP # 1 is a new variable of the type: CAP # 1 extends the class from capture? propagates class 1 error

Please help me fix the code. What am I missing? Thanks.

+4
source share
1 answer

You are comparing Outer.Inner.class with objTyp.getClass() instead of objTyp .

  • objTyp is of type Class<Outer.Inner> .
  • objTyp.getClass() is of type Class<Class<Outer.Inner>> .
  • Outer.Inner.class is a class literal of type Class<Outer.Inner> .

Therefore, objTyp.getClass() has no chance to equal Outer.Inner.class .

  Outer outObj = new Outer(); Outer.Inner inObj = outObj.new Inner(); // Using Reflection Class objTyp = inObj.getClass(); System.out.println(objTyp.getName()); // >>>>> objTyp is already inObj.getClass() <<<<<< if(objTyp.getClass() == Outer.Inner.class){ System.out.println("Match classes!"); }else{ System.out.println("Mismatch classes!"); } 
+7
source

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


All Articles