Here's a small code I wrote to check the (is it called reflection API? not sure) classes at runtime, however I am not getting the intended 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 fresh type-variable: CAP#1 extends Class from capture of ? extends Class 1 error
Please help me to correct the code. What am I missing? Thanks.
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>
.Hence, 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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With