Home > Mobile >  How to convert an Element to a Method?
How to convert an Element to a Method?

Time:12-31

I'm building an annotation processor for an annotation called "Auditable". The processor gets invoked by the builder (some parts are left out for easier reading):

@Override
public boolean process( Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv ) {

    //--- Obtain all annotated elements
    Set<? extends Element> annotatedElements =
            roundEnv.getElementsAnnotatedWith( Auditable.class );

    //--- Separate elements into classes, fields and methods
    for ( Element element : annotatedElements ) {
        ElementKind kind = element.getKind();
        if ( ElementKind.METHOD.equals( kind ) ) {
            checkAndAddMethod( element );  // <-- Must convert Element to Method
        } 
    ... }

void checkAndAddMethod( Method method ) {  // <-- parameter type = Method

How can I convert the annotated Element to a Method?

CodePudding user response:

If an annotation has enough data like class name, method name, and arguments etc., then the below snippet can get you a Method object.

String className = // Get from the annotation attribute
String argumentClassName = // Get from the annotation attribute
String methodName = // Get from the annotation attribute

Class myClass = Class.forName(className);
Class argumentClass = Class.forName(argumentClassName);
Method method = myClass.getDeclaredMethod(methodName, argumentClass);

Refer this link1, link2 for an example.

CodePudding user response:

I don't think you can, because the language model represents code, and reflection represents the running JVM. Can you perhaps work with ExecutableElement instead? That represents a method, constructor or initializer as part of the language model.

  • Related