Suppose I have two classes A and B. Both are identical (same atributes, methods, etc), but they are named different.
There's some safe way, in Java, to cast a B object as an A object?
No, you cannot cast one to the other if they belong in different class hierarchies. They are not identical, even if they happen to share the same attributes and methods. Additionally, if they belong to the same class hierarchy, but one is not a superclass of the other, you can't cast across the same class hierarchy either. There's only upcasting and downcasting within a hierarchy.
However, you can pass objects of either class to a certain method if
(And that's the basic premise of polymorphism.)
No you can't, unless they have a common parent with the same attributes, but you can use the copyProperties()
method from common.beanutils to pass every property from one bean to another.
Another way would be to create a subclass for A which could delegate calls to a B and vice versa.
A third way would be to use a proxy.
But the last two solutions only works for method calls, if your attributes are public you can't do anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With