Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto constraint name resolution for extracting method references [concept] #115

Closed

Conversation

seregamorph
Copy link

@seregamorph seregamorph commented Apr 16, 2021

Documentation defines constraint like this:

    .constraint(User::getName, "name", c -> c.notNull()
        .lessThanOrEqual(20))

The suggested draft implementation enhances the way to define a constraint:

    .constraint(User::getName, c -> c.notNull()
        .lessThanOrEqual(20))

How it works. The lambda method reference User::getName passed as ToCharSequence is resolved via new LambdaUtils.unreferenceLambdaMethod. It uses java.lang.invoke.SerializedLambda that allows to extract method information at runtime, then take the method name "getName" and finally resolve it as "name" constraint (cuts getter prefix).

Pros:

  • LambdaUtils is validated on a wide range of cases, so it looks reliable
  • LambdaUtils implementation is forward-compatible to Java 1.8 and higher (really make sense in comparison with other approaches to resolve the method reference)
  • The implementation should be runtime-safe, the expected worst case is non-perfect diagnostics (missing real extracting method name)

Cons:

  • Unclear policy how to handle non-method reference lambdas, like:
user -> user.getName()

For now it is just stubbed as "extracted" string.

Please note, that this implementation is an incomplete PoC, so let me know what do you think and in case of green light I'll finish it.

@making
Copy link
Owner

making commented Apr 16, 2021

wow, very interesting.
It looks like you're using reflection, is reflection required?

@seregamorph
Copy link
Author

At least I do not know a better way to resolve the method reference, so yes, it's required to call a private method.
I've checked it on Java 11 and 15. Java 16 build does not work (but there are other issues like maven and kotlin incompatibilities), so I cannot make a fair check.

@making
Copy link
Owner

making commented Apr 16, 2021

The idea is interesting but reflection is one of the things I would like to avoid introducing to YAVI.
That's why I brought Annotation Processor instead. https://github.com/making/yavi/blob/develop/docs/AnnotationProcessor.md

@seregamorph
Copy link
Author

Well, for now I do not have any better solution. So it's up to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants