Search code examples
javabean-validationbyte-buddy

Java JSR-303 Automatic Bean Validation without Byte Code Weaving


Is there a way to perform (more or less) "automatic" JSR-303 java bean validation without runtime modification of a class?

Usually I see people using AspectJ to accomplish this, but we have had so many complications when using runtime code weaving (like with cofoja) that I'd like to avoid it. It makes a lot of our build tools fail because the runtime class files were different than the class files on disk.

I've looked at dynamic proxies via reflection which can only proxy interfaces (public methods) AND if you call anything annotated inside "this", you don't go through the proxy anymore so you lose that validation.

I'v also looked at ByteBuddy for a way to possibly intercept method calls by wrapping/redefining a class. There might be something here but I can't figure out how to intercept private methods or accomplish the above without getting back into modifying the original class.

Any ideas?


Solution

  • In theory, you can enforce bean validation by reflection only. But I assume that by automatic, you mean without an explicit call to a validation method.

    In this case, instrumentation is probably your only option. With Byte Buddy, you can instrument existing methods, by using redefinition or rebasing. The easiest way to do so is a Java agent using an agent builder or using the Gradle or Maven plugins for build time instrumentation. The documentation provides an example of how to implement an agent and the build instrumentations have a lot of javadoc (documentation in progress).