Search code examples
javaobjectintrospection

Introspection in Java


I have a stack of Objects, in this stack I push ClassA and ClassB objects. I have a method which must return objects from this stack

public Object method(Stack s){
    ClassA a = new ClassA();
    stack.push(a);
    ClassB b = new ClassB();
    stack.push(b);
    while(stack has two elements) stack.pop();
    return stack.pop()// I return the last element
}

the problem is: when I call this method instanceof doesn't work, it can't tell anymore ClassA from ClassB

Object o = method(s);
if ( o instanceof ClassA){
    //do something
} else if (o instanceof ClassB) {
    //do something else
}

Inside method(Stack s) instanceof works, outside doesn't, but the toString() method works fine, it return the proper String for each class.


Solution

  • There are a few scenarios where your introspection code may not work as you expect:

    • If o is null, the instanceof operator returns false. The null value is not an instance of any type ... according to the JLS.

    • If ClassB is a subtype of classA, then o instanceof ClassA will return true for an instance of ClassB.

    • If you are doing something complicated with classloaders, it is possible to load the same ".class" file with different class loaders. If you do that, you will run into the problems that the two "copies" of the class actually have different types ... and instanceof will return false. (This behaviour is also specified in the JLS.)

    The last case can be particularly confusing, because when you look at the names of the two classes they will be the same. However class1.equals(class2) or class1 == class2 will give you the definitive answer about whether two classes are actually the same.