Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java reflection annotated fields/methods


How to use Java Reflection to find annotated fields and/or methods? java.lang.reflect provides means to do it fairly easily as can be seen in the following example.


Let’s create a sample annotation that we’ll use to mark fields and methods that we want to find:


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// Make the annotation available at runtime:
// Allow to use only on methods and fields:
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Findable {

     * User friendly name of annotated class.
    String name();

Retention is set to RUNTIME, because we want to access this meta information from running application. If the scanning is performed during some other stage, then it can be changed appropriately.

Now, sample Java class with annotated field and method. We use mechanisms from java.lang.reflect package to get all fields and methods from a class. Then both will be processed in the same way – check if annotation is present and if so, process it:


import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;

public class ReflectAnnotatedMembers {

    public static class MyClass {

        private int notFindable = 123;

        @Findable(name = "The X field")
        private int x = 42;

        @Findable(name = "Addition")
        public int add(int a, int b) {
            return a + b;

    public static void main(String[] args) {

    private static void findAnnotatedFields() {
        for (Field f : MyClass.class.getDeclaredFields()) {
            processAnnotation(f, f);

    private static void findAnnotatedMethods() {
        for (Method m : MyClass.class.getDeclaredMethods()) {
            processAnnotation(m, m);

    private static void processAnnotation(Member member, AccessibleObject obj) {
        if (obj.isAnnotationPresent(Findable.class)) {
            Findable meta = obj.getAnnotation(Findable.class);
            String className = obj.getClass().getSimpleName();
            System.out.printf("Found %s: %s, with name: %s%n",
                    className, member.getName(),;

We have to pass the java.lang.reflect.Field and java.lang.reflect.Method twice, because getAnnotation() and getName() are declared on different interfaces – java.lang.reflect.AccessibleObject and java.lang.reflect.Member.

And here’s the result of finding annotated fields and methods:

Found Field: x, with name: The X field
Found Method: add, with name: Addition

Simple, isn’t it? :-)

If you need to work with Java Reflection then consider using Apache Commons Lang3 or Reflections libraries. Both make it a lost easier, which we’ll show in future posts.

Share with the World!