Reputation: 1304
@Data
public class MyData {
private long a;
private long b;
private long c;
}
if we want to update all the field of a,b,c, then code could be like below:
MyData d;
...
d.setA(d.getA()+2);
d.setB(d.getB()+5);
d.setC(d.getAC()+8);
in other language, we may write code like:
d.a += 2;
d.b += 5;
d.c += 8;
Any graceful way to do update with this mode in java?
Upvotes: 1
Views: 685
Reputation: 4114
While you could make your fields public:
public class MyData {
public long a;
public long b;
public long c;
}
and then just
MyData d;
//...
d.a += 2;
d.b += 5;
d.c += 8;
a better approach would be to introduce increment methods:
public class MyData {
private long a;
private long b;
private long c;
public void incrementA(long x){
a += x;
}
public long incrementAndGetA(long x){
a += x;
return a;
}
public void incrementB(long x){/*...*/}
public long incrementAndGetB(long x){/*...*/}
}
and then...
MyData d;
//...
d.incrementA(2);
long bb = d.incrementAndGetB(4);
This approach will maintain encapsulation. Obviously you can add decrement methods (or just use negative values).
Upvotes: 1
Reputation: 14999
You could provide an access method
public void manipulateX(Function<Integer, Integer> manipulator) {
x = manipulator.apply (x);
}
You can then call that with mc.manipulateX(i -> i+ 2)
.
Upvotes: 0
Reputation: 140427
The other answers are all technically correct, but to give some conceptual thoughts: what you are thinking of/asking for is called Uniform Access Principle - the idea that reading and writing to a field follows the same syntax. Respectively the idea that x.y
and x.y()
can actually mean the same thing.
And for good or bad, Java does not support that concept on the syntactical level, and lombok doesn't help here either.
If you want to assign a value to a field, you either need an explicit setter (or maybe increment) method, or you need to make the field public
.
End of story.
Upvotes: 2
Reputation: 11600
You can simply create a dedicated method:
public class MyData {
private long a;
...
// use setter to set value
public void setA(long value){
this.a = value;
}
// add to current value
public void addToA(long value){
this.a += value;
}
...
}
You could also make those fields public, it comes to your choice.
But methods can do more things, like validate input values. It's also a way of encapsulating values inside of the class, and let smart methods to modify their values.
You can also modify Lombok builder to have a custom setter. You can find a thread on this here
@Builder
class MyData {
....
public static class MyDataBuilder {
public MyDataBuilder a(long value) {
this.a = value;
return this;
}
}
}
Upvotes: 0
Reputation: 49
you can write a function about that.
@Data
public class MyData {
private long a;
private long b;
private long c;
void add(long number1, long number2, long number3){
a += number1;
b += number2;
c += number3;
}
}
You can also use negative numbers for extraction.
Upvotes: 0