Java Annotations Processor: Check if TypeMirror implements specific interface

annotation-processing, annotations, java, reflection

Solution

Instead of checking the direct supertypes, you should use `Types.isAssignable` to check if `Serializable` is one of the supertypes of the `TypeMirror`:

TypeMirror serializable = elementUtil.getTypeElement("java.io.Serializable").asType();
boolean isSerializable = typeUtil.isAssignable(tm, serializable);

Problem

I'm working with on a Java annotations processor. My annotation, `@foo` is used to mark field variables that can be read to a file or from a file during runtime. However, I would like to check if the variable type implements `Serializable` during compile time, so that if the field is not serializable I can give a warning/error at compile time. (I don't need to actually check if the object IS serializable, if it implements the `Serializable` interface I'll trust it). I have figured out how to do the other stuff, but I can't figure out how to check if the element implements `Serializable`. I can use the `TypeElement#getInterfaces` method, but I can't figure out how to check if any of these `TypeMirror`'s returned are the one for `Serializable`. Also, if anybody happens to know any good `java.lang.model` or Java Annotations tutorials, that would be helpful as well. Edit: I have tried this... ``` isSerializable = false for(TypeMirror tm : processingEnv.getTypeUtils().directSupertypes(em.asType())) { if(isSerializable = "java.io.Serializable".equals(tm.toString())) { break; } } ``` It works alright for String and Character, which directly implement `Serializable`, but for Integer, which inherits Serializable from the Number superclass, it does not work.

Original source