简体   繁体   English

有没有一种方法可以模拟Java中的属性选择器?

[英]Is there a way to simulate property selectors in java?

In C# we have the option to specify a property of an object using property selectors (for example when using LINQ) like so: 在C#中,我们可以选择使用属性选择器指定对象的属性(例如,使用LINQ时),如下所示:

var usernames = customers.Where(x => x.Age > 20).Select(x => x.Username);

Here we first select the property Age to perform the comparison on and then specify the property Username to the Select(...) clause. 在这里,我们首先选择属性Age进行比较,然后将属性Username指定给Select(...)子句。

I am currently trying to replicate this functionality using lambda expressions in Java to enable users of my code to specify which property should be used for some action later on. 我目前正在尝试使用Java中的lambda表达式来复制此功能,以使我的代码的用户可以指定稍后应使用该属性进行某些操作。 The final result should look similar to the following: 最终结果应类似于以下内容:

public class Builder<T> {

// ...
private Field field;

Builder<T> forField(SomeFunctionalInterface s) {
    this.field = s.evaluate();
    return this;
 }
// ...
}

Thank you for your effort. 感谢你的付出。

The example below will compile without error: 下面的示例将编译而不会出现错误:

public void test() {
  from(Customer.class).where(c -> c.getAge() > 20).select(Customer::getUserName);
}

public <T> Builder<T> from(Class<T> cls) {
  return new Builder<>(cls);
}

public class Builder<T> {
  private Class<T> cls;

  public Builder(Class<T> cls) {
    this.cls = cls;
  }

  public Builder<T> where(Predicate<T> predicate) {
    // store predicate
    return this;
  }

  public Builder<T> select(Function<T, Object> field) {
    // store field selector
    return this;
  }
}

public class Customer {
  private String userName;
  private int age;

  public int getAge() {
    return age;
  }

  public String getUserName() {
    return userName;
  }
}

You can't access private fields directly though, you need a getter for them. 但是,您不能直接访问private字段,您需要为它们获取一个getter。

您可以为此使用流API:

customers.stream().filter(customer => customer.getAge() > 20).map(Customer::getUserName).collect(Collectors.toList())

I'm the author of Linq to Objects(Java). 我是Linq to Objects(Java)的作者。 You can use lombok and Linq to impl this. 您可以使用lombok和Linq来实现。

val result = Linq.asEnumerable(customers).where(customer -> customer.getAge() > 20).select(customer -> customer.getUserName());

lombok 龙目岛

Linq 林克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM