简体   繁体   中英

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:

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.

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. 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.

您可以为此使用流API:

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

I'm the author of Linq to Objects(Java). You can use lombok and Linq to impl this.

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

lombok

Linq

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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