Java – how to interpret a simple setter as a consumer?

First, please wait patiently Most of the time I work in scala (sometimes only on the JVM side) or other languages, so my knowledge of Java (8) is a little limited!

The code I had to refactor was full of empty checks I want some POJOs to have better property settings / overrides, and I'm happy to use Java 8 to get things done

So I created this:

private <T> void setOnlyIfNotNull(final T newValue,Consumer<T> setter) {
    if(newValue != null) {
        setter.accept(newValue);
    }
}

And use it like this:

setOnlyIfNotNull(newUserName,user::setName);

Junit4 test looks like this:

@Test
public void userName_isOnlyUpdated_ifProvided() {
   User user = new User("oldUserName");

   UserUpdateRequest request = new UserUpdateRequest().withUserName("newUserName");   
service.updateUser(user,request); // This calls setOnlyIfNotNull behind the curtain. And it does invoke the setter ONLY once!

 assertThat(user.getUserName()).isEqualTo("newUserName");
}

It works Before I asked my colleagues for code review, I was very satisfied with myself After explaining what I did, he explained in detail that he thought it didn't work because the function still didn't have a first-class citizen in Java, and the user POJO didn't extend the functional interface Interfaces are also provided at the class level rather than at the functional level

Now I want to know why the testing work, what I abused here? Naive me just imagines that the java compiler knows that the T sett (t value) signature of the setter is the same as that of the consumer < T >

Edit: Details: if I change the test to fail, for example, with assertthat (user. Getusername()) isEqualTo(“Something”); Failed comparison failed as expected!

Solution

This comment is wrong in the following aspects:

>Functional interface is not required for interface functions It is just a compiler prompt. When the content marked with this annotation does not meet the conditions (just the interface of an abstract method), it marks an error

>In any case, the user should not be functional. It is the consumer interface, which is functional. > Although the function may not be the first type of value (although see here for more information), user:: setfoo is not a "raw" function. It is a construct that creates an object that implements consumer (in this case) and calls user with any parameters passed in setFoo(). This mechanism is ostensibly similar to how anonymous inner classes declare classes and immediately create instances (but there are significant differences in the mechanism behind it.)

But the most powerful argument is that your code can only be proven effective using Java's official and documented APIs So it's a strange idea to say "but Java doesn't support this"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>