emorisse
emorisse

Reputation: 13

When I try to know if there is an annotation in my method, it returns null (even when there is one)

In a bukkit project, something to simplify the creation of commands, I did something that worked but I want to try new things (to learn how to use these things: Annotations!!) but in my code when I look in my code if there is an annotation "Command" on my method it returns "null" and I do not understand why 🤔

My code that looks for the annotation "Order" in my class :

for(Method method : clazz.getMethods()) {
    Command ann = method.getAnnotation(Command.class);
    if(ann != null) {
         // Creates the command
    }
}

My annotation class :

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

@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}

I hope you'll help me find out where my mistake is. And I want to apologize for my English because I am a kind of French and I know that my English is not very good:/

PS: I am a young developer so don't blame me if the answer is obvious, I try to learn by myself, everything I have learned is not with a teacher or another....

Upvotes: 1

Views: 61

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 9492

You need to mark your annotation with @Retention(RetentionPolicy.RUNTIME) in order to be available for query in runtime.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}

Upvotes: 3

Related Questions