共計 868 個字符,預計需要花費 3 分鐘才能閱讀完成。
可以使用反射機制來獲取注解標注的方法。
首先,需要獲得要獲取注解的類的 Class 對象,可以通過類名.class 或者對象.getClass()方法來獲取。然后,通過 Class 對象的 getMethods()方法來獲取該類的所有公共方法。接著,遍歷這些方法,可以通過 Method 對象的 getAnnotation()方法來獲取方法上的指定注解。
以下是一個示例代碼:
import java.lang.reflect.Method;
public class AnnotationExample {@MyAnnotation
public void myMethod() {// 方法體
}
public static void main(String[] args) throws NoSuchMethodException {
Class<AnnotationExample> clazz = AnnotationExample.class;
Method[] methods = clazz.getMethods();
for (Method method : methods) {if (method.isAnnotationPresent(MyAnnotation.class)) {MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Method " + method.getName() + " has annotation " + annotation.value());
}
}
}
}
在上面的代碼中,定義了一個自定義注解 @MyAnnotation
,然后在myMethod()
方法上使用了該注解。在 main 方法中,通過反射獲取了 AnnotationExample
類的所有方法,并判斷每個方法是否有 @MyAnnotation
注解,如果有,則打印出方法名和注解值。
注意:獲取到的方法包括了父類中的方法,如果只想獲取當前類中的方法,可以使用 getDeclaredMethods()
方法。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完