Accessing object Field and their Annotations

java

(Kad) #1

Hello,
I am trying to detect, if a field (that is being called by its getter), has a certain annotation (In this case : NotGoodAnnotation).

Example:

class MyClass { 
    	MyClass(){
    		
    	}
    	
    	void methodDefaulSequence() {
    		classX x = new classX();
    		
    		x.getB(); //=> an alert should be raised here
    	}

    }

class classX  {
    @NotGoodAnnotation
     private int b;

     public int getB(){
        	return b;
     }
}

I don’t seem to know from where to start !
Any help would be much appreciated !


(Tibor Blenessy) #2

Hello,

I assume you already read through basic documentation .

There are few assumptions you will need to make about structure of your code to simplify things, like getters are named correctly, etc. Following snippet should achieve what you are trying to do (if I understood correctly)

    MethodInvocationTree methodInvocationTree = (MethodInvocationTree) tree;
    String methodName = methodInvocationTree.symbol().name();
    // detect getter invocation by method name (should also consider is*** )
    if (methodName.startsWith("get")) {
      // it's a getter, we will find field by using the name
      String fieldName = methodName.substring(3);
      Symbol.TypeSymbol methodCLass = (Symbol.TypeSymbol) methodInvocationTree.symbol().owner();
      // let's assume there is only one result
      Symbol field = methodCLass.lookupSymbols(fieldName).iterator().next();
      // test annotation by calling Symbol.metadata()
      if (field.metadata().isAnnotatedWith("org.example.NotGoodAnnotation")) {
        reportIssue(tree, "Field is annotated with NotGoodAnnotation");
      }
    }

(Kad) #3

Looks like a winner ! Will test it, and get back at you ASAP.
Thanks


(Kad) #4

It’s exactly that ! Thanks a lot ^^