Skip to content

Instantly share code, notes, and snippets.

@DarkGuardsman
Last active June 20, 2018 12:52
Show Gist options
  • Save DarkGuardsman/2d5869ecb8c1993dc6fb6fb3c0500d53 to your computer and use it in GitHub Desktop.
Save DarkGuardsman/2d5869ecb8c1993dc6fb6fb3c0500d53 to your computer and use it in GitHub Desktop.
Test to see if annotations can be found on subclass methods that were added on superclass methods
package com.buildbroken.tests;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
List<Method> methods = getMethodsWithAnnotation(Alpha.class);
System.out.println("Found: " + methods);
Alpha alpha = new Alpha();
for(Method method : methods)
{
try
{
method.invoke(alpha);
}
catch (Exception e)
{
e.printStackTrace();
}
}
methods = getMethodsWithAnnotation(Beta.class);
System.out.println("Found: " + methods);
Beta beta = new Beta();
for(Method method : methods)
{
try
{
method.invoke(beta);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static Method[] getAllMethods(Class clazz)
{
return clazz.getMethods();
}
public static List<Method> getMethodsWithAnnotation(Class clazz)
{
List<Method> list = new ArrayList();
Method[] methods = getAllMethods(clazz);
for (Method method : methods)
{
System.out.println("Method: " + method.getName());
FindMe findMe = method.getAnnotation(FindMe.class);
if (findMe != null)
{
list.add(method);
}
}
return list;
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public static @interface FindMe
{
}
public static class Alpha
{
@FindMe
public void targetMethod()
{
System.out.println("Something something dark side");
}
}
public static class Beta extends Alpha
{
@Override
public void targetMethod()
{
System.out.println("Something something light side");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment