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?
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.
Probably, you could use reflection to copy properties. Then, create a wrapper function to "cast" the class; example:
class A {
public cc=0;
}
class B {
public cc=2;
}
B mycast(A a){
B b=new B();
for(String name in a)
b.setProperty(name,a.getProperty(name));
return b;
}
Notes:
Formally speaking the only way two Java classes can be identical is if they satisfy the identity a == b. Two classes with the same members and different names or packages don't do that, also by definition.