Roxana
Roxana

Reputation: 1581

How to copy nicely the fields from a base class into the dervived class?

I have a base class A and a derived class B. How can I copy...in a single simple line...the fields from an object of type A into an object of type B? I have a method,if that helps,that can build the object from the field values. I do not want to use any type of reflection!

class A{
  String id; //and setter/getter
 }
class B extends A{
  String b; //and setter/getter
}
public A buildA(String id){
  A=new A();
  a.setId(id);
  return A();
}
// how to copy A=buildA("a") into a B type of object...
// I would avoid doing 
//public B voidB(String id, string b){
B=new B();
b.setId(
b.setB...
// Remark - I cannot do the init from constructor with fields!

Upvotes: 0

Views: 300

Answers (2)

Puce
Puce

Reputation: 38122

There is a library called Dozer, which might help you (i haven't tried it, though).

Upvotes: 1

VijayD
VijayD

Reputation: 820

Is this what you are looking for, or am i on the wrong track?

public B buildB(A a,String str){
b=new B();
b.setId(a.getId());
b.setB(str);
return B;
}

Upvotes: 0

Related Questions