0

Using java reflection

class A {    
  @two    
  public method1()  {    
  }    

  @one    
  public method2()  {    
  }

  @two    
  public method3()  {    
  }

  public method4()  {    
  }      
 }

In the above given example of the code I want to retrieve annotated methods,non-annotated methods and all types of methods present inside a class as per the choice made by the user. for example- In the example given above I want to retrieve only annotated methods of the class A or only non-annotated methods of the class A or all the methods present inside class A. What should be the code for this example.

can someone please help me out...

SonalPM
  • 1,317
  • 8
  • 17
ajay
  • 17
  • 7
  • 1
    There are quite a few examples of searching for annotated methods take a look at this post http://stackoverflow.com/questions/6593597/java-seek-a-method-with-specific-annotation-and-its-annotation-element or the following http://www.java2s.com/Code/Java/Reflection/FindAnnotatedMethod.htm – Kenneth Clark Nov 18 '14 at 06:54
  • You should at least try something. The javadoc of Class and Method has all you need to know. – JB Nizet Nov 18 '14 at 06:57

1 Answers1

0
 public static void main(String[] args) throws Exception {

        Class clazz = B.class;

        List<Method> allMethods = new ArrayList<Method>(Arrays.asList(clazz.getDeclaredMethods()));
        try {
            for (Method method : allMethods) {
                method.setAccessible(true);
                if (null != method.getAnnotations() && method.getAnnotations().length > 0) {
                    Annotation[] annotations = method.getAnnotations();
                    System.out.println(method.getName());
                    for (Annotation annotation : annotations) {
                        System.out.println(annotation);
                    }

                } else {
                    System.out.println(method.getName());
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

public class B {

    public void getValue() {

    }

    @Deprecated
    public void getValue1() {

    }
}

output

getValue
getValue1
@java.lang.Deprecated()

Points to remember

1.) The above approach make use of Java Reflection.

2.) java.lang.reflect.Method has two methods getAnnotations() and getDeclaredAnnotations(), which can be used according to need. Please read Javadoc for details.

3.) It also has isAnnotationPresent() method which checks for specific annotation on a moethod.

4.) The abovecan be used to access field and method properties both.

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116