Foo can't be dropped on Foo

I pass through an ArrayList<Bar> . Foo continues to Bar . I am trying to find an instance of Foo in the list.

 ArrayList<Bar> list = new ArrayList<Bar>(); // fill list with items that are instances of Foo and Bar for (int i = 0; i < list.size(); i++) { Bar bar = list.get(i); if (bar.getClass().getName().equals("com.me.Foo")) // "if(bar instanceof Foo)" never passes { System.out.println("bar is an instance of Foo"); Foo foo = (Foo) bar; } } 

If this section of code starts, I get this error:

 java.lang.ClassCastException: com.me.Foo cannot be cast to com.me.Foo // stack 

However, in another place, I have a method that returns an instance of Bar , and I can check if it is an instance of Foo using instanceof , and then drops Bar in Foo using no problem:

 Bar bar = returnBar(); // returns an instance of Bar, but the variable // it returns could be an instance of Foo if (bar instanceof Foo) { System.out.println("bar is an instance of Foo"); Foo foo = (Foo) bar; } 

What is different here?

Here's the real source of the problem: http://pastie.org/private/jhyhovn7mm4ghxlxsmweog

I am working with an API called Bukkit, which allows you to configure server plugins for a game called Minecraft. Documentation can be found here for those who are really interested in this issue. I'm going to go to the official Bukkit forums and try my question there, as it becomes an increasingly API-specific problem, but I will leave it all here for those interested in this problem.

+8
java casting
source share
1 answer

I assume that you download Foo from two places. In your loop, try printing bar.getClass().getClassLoader() and Foo.class.getClassLoader() . I suspect they will show different class loaders. (Perhaps you have loading two classloaders from the same place, which is equally bad.)

Basically, with regard to the JVM, two classes with the same name loaded from different class loaders are completely different - you cannot drop them from one to another. Assuming I'm right about this, the usual solution is to try to find out why they are being loaded from different class loaders and fix it.

Note that using instanceof instead checks to see if the types are really compatible, so it will notice different class loaders.

+17
source share

All Articles