2012-06-14 45 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) 
    } 
} 
相关问题