Skip to content

Annotation Discovery

Hempfest edited this page Oct 8, 2021 · 1 revision

In labyrinth a tool is accessible to you that allows you to manipulate annotations/methods/classes all in one go AnnotationDisovery<? extend Annotation, R>

Writing an annotation

You may already have an annotation you'd like to use so if that's the case you can skip this part all together!

We're gonna start by making an annotation class called Test in this class we'll store one value (a String). One tip to know about annotations is they are semi-limited with the type of members allowed within them. Annotations can only contain primitive types or class objects, another tip would be that you can safely imply a value assignment without key declaration for your annotation as-long as the primary value being used is name value.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {

	String value();

}

Now we can use this exact annotation the follow ways:

w/ value:

@Test("Hello")
public void thing() {}

w/ out value:

@Test()
public void thing() {}

If we were to call the value in our annotation something other than value our result would be this:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {

	String key() default "";

}
@Test(key = "Hello")
public void thing() {}

Using the annotation

Now that we have our annotation ready to use lets fill out some information!

Using the static of instance from the discover class go ahead and filter your methods to your liking, when done we can access the information we need! Im just going to use the Test annotation from above.

AnnotationDiscovery<Test, Object> discovery = AnnotationDiscovery.of(Test.class, yourObjectOrClassToSearch).filter(true);
for (Method m : discovery) {
  Test t = m.getAnnotation(Test.class);
  String value = t.value();
}