Personal casting classes?

Suppose I have two classes A and B. Both of them are the same (same attributes, methods, etc.), but they are called different.

Is there any safe way in Java to create object B as object A?

+3
source share
5 answers

No, you cannot drop one on another if they belong to different class hierarchies. They are not identical , even if they have the same attributes and methods. In addition, if they belong to the same class hierarchy, but one is not a superclass of the other, you also cannot use the same class hierarchy. There is only rise and fall in the hierarchy.

,

  • ,

( polymorphism.)

+7

, , , copyProperties() common.beanutils bean .

- A, B .

- proxy.

, , .

+3

, . "" ; :

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;
}

:

  • , Java, , JS.
  • ; , , ( , ).
+1

, , Java, - , a == b. , .

0

The only way is to manually set the data in class A to the data of class B

0
source

Source: https://habr.com/ru/post/1768796/


All Articles