How do I create a type of one class but from a different package in Java?

There are two classes

foo.bar.FileUploader

and barbar.foofoo.FileUploader

Both are identical and expandable Uploader

Somewhere in the code is used foo.bar.FileUploader

and set as a parameter to my function as a type Uploader

.

Now I need to put it back in FileUploader

but barbar.foofoo.FileUploader

. And this gives an error:

ERROR - unhandled error java.lang.ClassCastException

: foo.bar.FileUploader

cannot be added beforebarbar.foofoo.FileUploader

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

+2


source to share


6 answers


Thanks for helping people.



I just solved the problem by importing barbar.foofoo.FileUploader. It works great now!

-1


source


Technically, this is not the same class.



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

+7


source


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 classes is Lion

identical and they both implement a common interface, you cannot distinguish the other way around, for example

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

      

+4


source


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

If you want it to be identical then you have to make the same class, i.e. import via packages. It might be easiest to start refactoring so that one extends the other.

+2


source


Others have said this already: classes are not the same, simply because they look like this. Do classes develop / extend the same interface / abstract class? cast into an interface or abstract class, they both extend 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 indeed 100 percent identical, this is clearly a flawed design, remove one of the classes.

The Java Language specification describes what you are allowed to do and what is not.

+2


source


Get rid of duplicate code. Even if it works now, because both classes are identical, what happens if someone edits class A and forgets about class B?

edit: you say they are identical, so I think they are copies. That would be bad. But since they both expand Uploader

, you can use Uploader

instead FileUploader

.

+1


source







All Articles