Home > Enterprise >  Java: How can I efficiently match 2 classes member values partially?
Java: How can I efficiently match 2 classes member values partially?

Time:07-06

I have 2 classes (3rd party): one is representing a GET endpoint response, and the second one is representing a PUT endpoint body.

My aim is to get the resource current state using the get endpoint, and update it using the put endpoint.

It appears that the put class is a subset of the get class.

For example:

class A{
 int a;
 int b;
 int c;
}

class B{
 int a;
 int b;
 int c;
 int d;
}

So B "includes" the A members, and more.

In practice, B extends A (although meanwhile I didn't implemented this way).

So, what would be the correct way to handle the following situation?

Services serv = new Services();
A a = new A();
B b = serv.get();

/*

How do I update only the common members value of A object, except of using a long assignments list method? I mean, I can create this kind of a method:

private void adjustAValuesAccordingToB(B b){

 a.val1 = b.val1;
 a.val2 = b.val2;
 a.val3 = b.val3;
 ...

}

But is there a cleaner way to handle this situation?

a.setVal3(x); //change val3 value

serv.put(a);

CodePudding user response:

I would just make a second constructor for A which takes a B instance.

class A {
    int a;
    int b;
    int c;
    public A(B b) {
        this(b.a, b.b, b.c);
    }
    public A(int a, int b, int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Then

B b = server.get();
A a = new A(b);

If you can't modify A, then you will need to just pass the elements of B directly to the existing constructor.

  •  Tags:  
  • java
  • Related