Skip to content

Instantly share code, notes, and snippets.

@cocoatomo

cocoatomo/Functor.java

Last active Sep 23, 2015
Embed
What would you like to do?
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@interface Functor {
@Target(ElementType.METHOD)
@interface Map {}
}
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.SourceVersion;
import javax.lang.model.type.ExecutableType;
import javax.tools.Diagnostic.Kind;
import java.text.MessageFormat;
import java.util.Set;
@SupportedSourceVersion(SourceVersion.RELEASE_8)
@SupportedAnnotationTypes({"Functor", "Functor.Map"})
public class FunctorAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
for (TypeElement typeElement : annotations) {
for (Element element : env.getElementsAnnotatedWith(typeElement)) {
Messager messager = super.processingEnv.getMessager();
messager.printMessage(Kind.NOTE,
MessageFormat.format("Kind : {0}\n"
+ "SimpleName : {1}\n"
+ "Modifiers : {2}\n"
+ "asType : {3}\n"
+ "EnclosedElements : {4}\n"
+ "EnclosingElements : {5}\n"
+ "AnnotationMirrors : {6}\n",
element.getKind(),
element.getSimpleName(),
element.getModifiers(),
element.asType(),
element.getEnclosedElements(),
element.getEnclosingElement(),
element.getAnnotationMirrors()));
if (element.getKind() == ElementKind.METHOD) {
ExecutableType type = (ExecutableType) element.asType();
messager.printMessage(Kind.NOTE, MessageFormat.format("parameterTypes : {0}\n"
+ "returnType : {1}\n"
+ "thrownTypes : {2}\n"
+ "typeVariables : {3}\n",
type.getParameterTypes(),
type.getReturnType(),
type.getThrownTypes(),
type.getTypeVariables()));
}
}
}
return true;
}
}
$ javac -processor FunctorAnnotationProcessor ListFunctor.java
Note: Kind : CLASS
SimpleName : ListFunctor
Modifiers : [public]
asType : ListFunctor<A>
EnclosedElements : ListFunctor(),<B>map(java.util.function.Function<A,B>)
EnclosingElements : unnamed package
AnnotationMirrors : @Functor
Note: Kind : METHOD
SimpleName : map
Modifiers : [public]
asType : <B>(java.util.function.Function<A,B>)ListFunctor<B>
EnclosedElements :
EnclosingElements : ListFunctor
AnnotationMirrors : @Functor.Map
Note: parameterTypes : java.util.function.Function<A,B>
returnType : ListFunctor<B>
thrownTypes :
typeVariables : B
import java.util.function.Function;
@Functor
public class ListFunctor<A> {
@Functor.Map
public <B> ListFunctor<B> map(Function<A, B> morphism) { return null; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment