下面是使用反射
public class Driver {
public static void main(String[] args) {
// get all methods
for (Method method : Driver.class.getDeclaredMethods()) {
// get your annotation
Annotation annotation = method.getAnnotation(Command.class); // reference could be of type Command if you want
if (annotation != null) {
// check if parameter exists
List<Class> parameterTypes = new ArrayList<Class>(Arrays.asList(method.getParameterTypes()));
if (!parameterTypes.contains(IssuedCommand.class)) {
System.out.println("trouble");
}
}
}
}
@Command
public void command(IssuedCommand cmd) {
}
public static class IssuedCommand {}
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.METHOD)
public @interface Command {}
}
您使用反射來得到你想要查詢的具體方法的工作示例。您可以通過檢查方法是否被註釋來做到這一點。然後可以比較方法參數列表中的類型。
在編譯時或運行時? –
我希望它在運行時。 –