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.

6
  • 1
    Are you getting some exception? Or any compiler error? Can you post the code where you are doing instanceof check? the method? Commented Oct 27, 2012 at 13:29
  • 2
    Are you certain that the method doesn't return null? Commented Oct 27, 2012 at 13:29
  • 1
    while(stack has two elements) seems to be quite strange as well Commented Oct 27, 2012 at 13:32
  • Yeah, it should be while (stack has two or more than two elements) Commented Oct 27, 2012 at 13:33
  • 1
    If the magic while is something like while (!stack.isEmpty()) then when calling return stack.pop() you will get an EmptyStackException. Commented Oct 27, 2012 at 13:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It was an error in my code, thank you btw for the explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.