我想创建一个注释,它搜索以注释中给出的单词开头的方法名称并执行此方法。
我是注释的新手,我知道有一些内置注释,例如:
@override, @suppressWarnigs, @documented, @Retention, @deprecated, @target
Run Code Online (Sandbox Code Playgroud)
有没有更多的注释?
我相信那里有很好的指南,但这里有一个快速指南,请原谅我的任何错别字:)。
您可以轻松创建自己的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExecuteMethod {
String methodToExecute();
}
Run Code Online (Sandbox Code Playgroud)
你可以用它来注释你的方法。
@ExecuteMethod(methodToExecute = "MethodToExecute")
...
Run Code Online (Sandbox Code Playgroud)
链接到注释的代码如下所示:
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
}
}
Run Code Online (Sandbox Code Playgroud)
您还需要一段代码来检查并在您希望完成的点执行此注释:
for(Method m : classToCheck.getMethods()) {
if(m.isAnnotationPresent(ExecuteMethod.class)) {
MethodExecturor methorExectuor = new MethodExecutor(m);
methodExecutor.executeMethod(m)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2223 次 |
| 最近记录: |