开发者

How to cast a type of same class but out of an other package in Java?

There are two classes

foo.bar.FileUploa开发者_C百科der and barbar.foofoo.FileUploader

Both are identical and extend Uploader

Somewhere in the code the foo.bar.FileUploader is used and are given as a parameter to my function as an Uploader type.

Now I need to cast it back to FileUploader but the barbar.foofoo.FileUploader. And this gives an error:

ERROR - unhandled error java.lang.ClassCastException: foo.bar.FileUploader cannot be cast to barbar.foofoo.FileUploader

And I can't figure out what's going wrong, I suppose it's because the package is different. In that case: Is there a way to still use the class and get the cast done?


Technically they're not the same class.

You're getting a ClassCastException because the JVM doesn't see them as the same type at all. Perhaps you should have both classes implement the same interface and cast to that? Or alternatively, just have one class in the first place and get rid of the cast?


For Java, the classes are not identical. Consider this

package zoo;
public interface Animal {}

package zoo.london;
public class Lion implements Animal{}

package zoo.newyork;
public class Lion implements Animal{}

Even if the implementation of both Lion classes is identical and they both implement a common interface, you can not cast vice versa like

zoo.london.Lion lion = (zoo.london.Lion) new zoo.newyork.Lion();  // ClassCastException


The two classes foo.bar.FileUploader and barbar.foofoo.FileUploader are NOYT the same as they are defined in different places with different names. Thus java thinks they have no relationship to each other,

If you want then to be identical then you have to make then the same class ie import across the packages. It might be easiest to start refactoring to make one of them extend the other.


Others already said it: The classes are not the same, just because they look like it. Do the classes implement/extend the same interface/abstract class? cast to the interface or abstract class they are both extended of and use that. What you are trying to do is simply not supported by the JVM. The JVM doesn't care if the classes are identical. If they are really 100 percent identical, it's clearly a messed up design, delete one of the classes.

The Java Language Specification describes exactly what you are allowed to cast and what not.


Get rid of duplicated code. Even if it would work now, because both classes are identical, what would happen if someone edited class A and forgot about class B?

edit: you say they are identical, so I guess they're copies. That would be bad. But since they both extend Uploader, you can cast to Uploader instead of FileUploader.


Thanks for the help people.

I just solved the problem by importing the the barbar.foofoo.FileUploader. Now it runs fine!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜