views:

55

answers:

4

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?

+4  A: 

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

  • They implement the same interface, or extend the same superclass, and
  • That method accepts a parameter that is of the interface's or superclass's type

(And that's the basic premise of polymorphism.)

BoltClock
+1  A: 

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.

Colin Hebert
+1  A: 

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:

  • Been some time since I've used Java, so the above should be seen as pseudo-code more or less, especially the JS-style reflection.
  • I suggest you use an interface instead; they were made specifically to do what you want (and more, of course).
Christian Sciberras
A: 

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.

EJP