Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Annotations Processor: Check if TypeMirror implements specific interface

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.

like image 755
Testare Avatar asked Dec 03 '13 17:12

Testare


People also ask

How annotation processors work?

The annotation processing is done in multiple rounds. Each round starts with the compiler searching for the annotations in the source files and choosing the annotation processors suited for these annotations. Each annotation processor, in turn, is called on the corresponding sources.

What is @interface annotation in Java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }

Are annotations compiled in java?

An annotation processor processes these annotations at compile time or runtime to provide functionality such as code generation, error checking, etc. The java. lang package provides some core annotations and also gives us the capability to create our custom annotations that can be processed with annotation processors.


1 Answers

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);
like image 145
kapex Avatar answered Sep 19 '22 17:09

kapex