lundi 17 octobre 2016

What is the easiest way to find and run private annotated method?

The following example runs MyClass#myMethod() only if it is public. It does not run it if it is private.

How to run even if private?

import org.apache.commons.lang3.reflect.MethodUtils;

import javax.annotation.PostConstruct;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by dims on 13.10.2016.
 */
public class CallPrivateMethodTest {

   @Retention(RUNTIME)
   @Target(METHOD)
   public @interface MyAnnotation {
   }

   public static class MyClass {

      @MyAnnotation
      private void myMethod() {
         System.out.println("myMethod() ran");
      }
   }

   public static void main(String[] args) {

      MyClass myObject = new MyClass();

      List<Method> methods = MethodUtils.getMethodsListWithAnnotation(myObject.getClass(), MyAnnotation.class);


      for(int i=0; i<methods.size(); ++i) {
         try {
            methods.get(i).invoke(myObject);
         } catch (IllegalAccessException e) {
            e.printStackTrace();
         } catch (InvocationTargetException e) {
            e.printStackTrace();
         }
      }
   }
}





Aucun commentaire:

Enregistrer un commentaire