Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java reflection annotated fields/methods

farenda 2015-08-21 0

Problem:

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.

Solution:

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

package com.farenda.java.lang.reflect;

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:
@Retention(RetentionPolicy.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:

package com.farenda.java.lang.reflect;

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) {
        findAnnotatedFields();
        findAnnotatedMethods();
    }

    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(), meta.name());
        }
    }
}

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!
Categories Java Tags java-lang
Previous: Java Reflection Generic Type
Next: Spring find annotated classes

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored