2012-06-14 141 views
-2

我想創建一個註釋,它從註釋中給出的單詞開始搜索方法名稱並執行此方法。如何在JAVA中使用邏輯創建自定義註釋

我是新來的註解,我知道有像一些內置的註釋:

@override, @suppressWarnigs, @documented, @Retention, @deprecated, @target 

是否有更多的註解?

+0

你應該試試GOOGLE吧! – plucury

+1

註解不執行代碼。註釋可以被代碼用來做事情。在得出結論之前,您需要閱讀更多關於註釋的內容,他們會解決您嘗試解決的任何問題。 – vanza

回答

1

我相信那裏有很好的導遊,但這裏有一個很快的導遊,請原諒我的任何錯別字:)。

您可以輕鬆創建自己的註釋:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface ExecuteMethod { 
String methodToExecute; 
} 

你可以用它來註解你的代碼。

@ExecuteMethod("MethodToExecute") 
... 

鏈接到註釋的代碼如下所示:

public class MethodExecutor{ 
private Method method; 

public MethodExecutor(Method method){ 
    this.method = method; 
} 

public boolean executeMethod(){ 
     if(method.isAnnotationPresent(ExecuteMethod.class)){ 
      ExecuteMethod executeMethodAnnot=method.getAnnotation(ExecuteMethod.class); 
      String methodName = executeMethodAnnot.methodToExecute(); 
      .... your code that calls the method here 
     } 
} 

還需要一段代碼來檢查並且該點處執行這個註解你想要它做:

for(Method m : classToCheck.getMethods()) { 
    if(m.isAnnotationPresent(ExecuteMethod.class)) { 
     MethodExecturor methorExectuor = new MethodExecutor(m); 
     methodExecutor.executeMethod(m) 
    } 
} 
相關問題