Is there a type that would hold all possible setter references of java class regardless of the type being set?

Ricardo Marimon :

Let's assume we have a very simple class:

public class User {

    private Long id;
    private String name;

    public void setId(Long id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

}

I'm doing a simple binder class to populate a user and would like to signal the required properties.

UserBinder binder = new UserBinder(user)
    .requires(User::setId)
    .requires(User::setName);

The above would signal that both properties are required. Of course I could pass the values "id" and "name" instead of the method references. But it seems that passing the setter is very appropriate since that setter needs to be called inside the binder.

The following works great:

public void requires(BiConsumer<User, Long> r) // for User::setId;
public void requires(BiConsumer<User, String> r) // for User::setName;

But the following fails:

public void requires(BiConsumer<User, ?> r)

Is there a type that would hold all possible setter references of java class regardless of the type being set?

caco3 :

You can add a generic parameter to the requires method:

public <T> void requires(BiConsumer<User, T> consumer)

Now this:

new UserBinder(new User())
    .requires(User::setName);

compiles fine.


You told that you need to store received consumers in some collection and check if the collection already contains some consumer

Unfortunately you can't do it easily (see this question).

As a workaround you can create a @FunctionalInterface extending Serializable with the same method signature as in the BiConsumer and compare serialized bytes. See this answer. But remember that you can't rely on this behavior

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76321&siteId=1