[hibernate-dev] Java 8, type annotations and Hibernate Validator

Emmanuel Bernard emmanuel at hibernate.org
Wed Apr 9 15:34:21 EDT 2014


Cool, I’ll be able to sleep tonight :)

On 09 Apr 2014, at 21:19, Gunnar Morling <gunnar at hibernate.org> wrote:

> 2014-04-09 21:01 GMT+02:00 Emmanuel Bernard <emmanuel at hibernate.org>:
> I always thought that type annotations would allow us to look via
> refection to annotations like
> 
>     public class Foo {
>        public Set< @NotNull String> names;
>     }
> 
> But looking at some tutorials like
> http://jaxenter.com/jsr-308-explained-java-type-annotations-49929.html
> 
> it seems that these annotations are only "visible" to a compiler plug-in
> / processor.
> 
> Am I right?
> 
> No, one can access type annotations at runtime (at least for fields, method signatures and so on) via reflection. A while ago I feared the same, so I asked on core-libs-dev [1] and got confirmation that it's possible. That's how you'd do it:
> 
>     // given    
>     private List<@NotNull String> names;
>     Field namesField = ...;
> 
>     // List<String>
>     AnnotatedParameterizedType type = (AnnotatedParameterizedType) namesField.getAnnotatedType();
> 
>     // String
>     AnnotatedType typeArg = type.getAnnotatedActualTypeArguments()[0];
> 
>     // @NotNull
>     Annotation annotation = typeArg.getAnnotations()[0];
> 
> It's one of the planned tasks of the HV GSoC project to make use of this to support constraints as in your example.
> 
> If that turns out true that would suck as it would only be useful to
> static tools. I wish I had checked the spec earlier to influence it :(
> 
> Emmanuel
> 
> --Gunnar 
> 
> [1] http://mail.openjdk.java.net/pipermail/core-libs-dev/2014-March/025732.html
>  
> _______________________________________________
> hibernate-dev mailing list
> hibernate-dev at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/hibernate-dev
> 



More information about the hibernate-dev mailing list