This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.customannotation; | |
import java.lang.annotation.*; | |
import java.lang.reflect.Method; | |
import java.util.ArrayList; | |
import java.util.List; | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.METHOD) | |
public @interface MyCustomAnnotation { | |
String name(); | |
String surname(); | |
} | |
class SomeClass { | |
@MyCustomAnnotation(name = "serkan", surname = "sunel") | |
public void someMethod(String someParameter) { | |
System.out.println("Hello annotation world !!" + someParameter); | |
} | |
} | |
class AnnotationProcessorWithReflection { | |
public static void main(String[] args) { | |
SomeClass someClass = new SomeClass(); | |
List<Method> methodsAnnotatedWith = getMethodsAnnotatedWith(someClass.getClass(), MyCustomAnnotation.class); | |
methodsAnnotatedWith.stream().forEach(m -> System.out.println(" Method name " + m.getName())); | |
} | |
private static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) { | |
final List<Method> methods = new ArrayList<>(); | |
Class<?> klass = type; | |
while (klass != Object.class) { | |
for (final Method method : klass.getDeclaredMethods()) { | |
if (method.isAnnotationPresent(annotation)) { | |
Annotation annotInstance = method.getAnnotation(annotation); | |
System.out.println("annotInstance = " + annotInstance + " found on the class: " + type); | |
methods.add(method); | |
} | |
} | |
klass = klass.getSuperclass(); | |
} | |
return methods; | |
} | |
} |
No comments:
Post a Comment