![](/img/trans.png)
[英]AspectJ: How to pick the execution of non-annotated methods of subclasses of a given class?
[英]how to retrieve annotated and non-annotated methods present inside a perticular class
使用Java反射
class A {
@two
public method1() {
}
@one
public method2() {
}
@two
public method3() {
}
public method4() {
}
}
在上面給出的代碼示例中,我想根據用戶的選擇檢索類中存在的帶注釋的方法,非帶注釋的方法以及所有類型的方法。 例如,在上面給出的示例中,我只想檢索類A的帶注釋的方法或類A的非帶注釋的方法或類A中存在的所有方法。本示例的代碼是什么。
有人可以幫我嗎...
public static void main(String[] args) throws Exception {
Class clazz = B.class;
List<Method> allMethods = new ArrayList<Method>(Arrays.asList(clazz.getDeclaredMethods()));
try {
for (Method method : allMethods) {
method.setAccessible(true);
if (null != method.getAnnotations() && method.getAnnotations().length > 0) {
Annotation[] annotations = method.getAnnotations();
System.out.println(method.getName());
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
} else {
System.out.println(method.getName());
}
}
} catch (Exception e) {
System.out.println(e);
}
}
public class B {
public void getValue() {
}
@Deprecated
public void getValue1() {
}
}
輸出
getValue
getValue1
@java.lang.Deprecated()
要記住的要點
1.)上述方法利用Java Reflection
。
2.) java.lang.reflect.Method
有兩個方法getAnnotations()
和getDeclaredAnnotations()
,可以根據需要使用。 有關詳細信息,請閱讀Javadoc。
3.)它還具有isAnnotationPresent()
方法,用於檢查方法上的特定注釋。
4.)以上內容可用於訪問字段和方法屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.