我想给对象的一个字段设置值,这样它就会首先获得该字段的前一个值,然后向其追加一些内容,然后将其设置到该字段。
在LambdaJ forEach中,我们可以这样做:
forEach(myCollection).setFieldValue("someValue");
但我需要的是:
forEach(myCollection).setFieldValue(getFieldValue() + "someValue");
在LambdaJ中是可能的吗?
发布于 2014-06-04 00:49:45
我知道你问过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);
}希望能帮上忙
发布于 2013-11-23 17:40:11
我有一个类似的用例,并意识到forEach对我使用它的方式没有帮助。
所以我认为闭包是一种解决方案:
@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);
}
}但是断言失败,因为集合中的对象没有被修改。也许我做错了什么。
最后,我使用了apache commons集合中的闭包。
更新
我能够用一个闭包来解决这个难题。看起来你不能直接使用自由变量。以下是工作代码:
@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);
}注意:除了this,您还可以编写一个包含visit方法的类,并在closure的定义中使用它。
https://stackoverflow.com/questions/19722880
复制相似问题