我想为对象的一个字段设置值,以便它首先获取该字段的先前值并将某些内容附加到它并将其设置到该字段。
在 LambdaJ 中forEach
,我们可以这样做:
forEach(myCollection).setFieldValue("someValue");
但我需要的是:
forEach(myCollection).setFieldValue(getFieldValue() + "someValue");
LambdaJ 有可能吗?
我想为对象的一个字段设置值,以便它首先获取该字段的先前值并将某些内容附加到它并将其设置到该字段。
在 LambdaJ 中forEach
,我们可以这样做:
forEach(myCollection).setFieldValue("someValue");
但我需要的是:
forEach(myCollection).setFieldValue(getFieldValue() + "someValue");
LambdaJ 有可能吗?
我知道你问过 LambdaJ,我很想这样做,因为这是一个常见问题。
我对我所做的结果感到惊讶:
forEach(list).setName(on(User.class).getName() + "someValue");
我虽然这将是你问题的答案。
因此,我通过使用 Guava 函数方式尝试了一种不同的方法。它可以为你工作,所以我会发布答案(但如果你不同意,我可以删除它):
番石榴功能方法:
@Test
public void test_applyPreviousValue() {
List<User> filteredList = Lists.newArrayList(new User("Fede", 20), new User("Peter", 12), new User("John", 41));
Function<User, User> getType = new Function<User, User>() {
public User apply(User input) {
input.setName(input.getName()+"someValue");
return input;
}
};
Collection<User> result = Collections2.transform(filteredList, getType);
System.out.println(result);
}
希望有所帮助
I had a similar usecase and realized forEach won't help the way I used it.
So I thought closures are a solution:
@Test
public void test() {
Closure modify = closure();{
of(Point.class).setLocation(var(Point.class).x+10, 10);
}
List<Point> points = new ArrayList<>();
points.add(new Point(10, 0));
points.add(new Point(10, 10));
modify.each(points);
for (Point point : points) {
assertEquals(20, point.getX(), 0.0);
}
}
But the asserts fails since the object in the collection is not been modified. Maybe I'm doing something wrong there.
In the end I used closures from the apache commons collection.
UPDATE
I was able to solve the puzzle with a closure. Looks like you can't use the free variable direct. Here is the working code:
@Test
public void test() {
Closure modify = closure();{
of(this).visit(var(Point.class));
}
List<Point> points = new ArrayList<Point>();
points.add(new Point(10, 0));
points.add(new Point(10, 10));
modify.each(points);
for (Point point : points) {
assertEquals(20, point.getX(), 0.0);
}
}
void visit(Point p) {
p.setLocation(p.x + 10, p.y);
}
Note: instead of this
you can also write a class which contains the visit
method and use it in the definition of the closure
.