0

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.

AR89
  • 3,548
  • 7
  • 31
  • 46
  • 1
    Are you getting some exception? Or any compiler error? Can you post the code where you are doing instanceof check? the method? – Rohit Jain Oct 27 '12 at 13:29
  • 2
    Are you certain that the method doesn't return null? – Fyodor Soikin Oct 27 '12 at 13:29
  • 1
    `while(stack has two elements) `seems to be quite strange as well – Thomas Jungblut Oct 27 '12 at 13:32
  • Yeah, it should be `while (stack has two or more than two elements)` – Rohit Jain Oct 27 '12 at 13:33
  • @FyodorSoikin yes, I'm certain, the toString method works. Thomas and Rohit, your suggestion is right, I will correct the code. I can't post all the code but I'm going to post a simple example in a few minutes. – AR89 Oct 27 '12 at 13:36
  • 1
    If the magic while is something like while (!stack.isEmpty()) then when calling return stack.pop() you will get an EmptyStackException. – Dan D. Oct 27 '12 at 13:37

1 Answers1

4

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216