我有以下情况:
,File2.java。Filen.java:我有不同的java文件,有不同的方法-- method1,method2 .方法。现在,这些文件中的一些方法被注释为@annotated_method。
现在我想创建一个java文件,它访问File1.java、File2.java .特定目录中的所有文件.Filen.java和我只需要对使用@annotated_method注释的方法进行分析(或进行一些处理)。分析(或该方法的处理)必须对每个注释的方法分别进行。
例如,
File1.java:
@annotated_method
method 1{
...
}
method 2{
...
}
.
.
.
@annotated_method
method 13{
...
}
.
.
.
method n
{
...
}
File2.java:
@annotated_method
method x1{
...
}
method x2{
...
}
.
.
.
@annotated_method
method x13{
...
}
.
.
.
@annotated_method
method xn
{
...
}如前所述,我只需要分析(或处理)方法1,13,x1,x13,xn。
如果我知道如何根据不同的需求进一步处理代码的注释部分,那就太好了。
我已经了解了getAnnotations();isAnnotationpresent()的用法;
发布于 2017-07-12 08:37:58
这可能对你有帮助:
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TimeMeasurer {
public static void gettimes(Class c) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
List<Method> methods=Arrays.asList(c.getMethods());
for(Method m:methods)
{
List<Annotation> ans= Arrays.asList(m.getAnnotations());
List<Class> classes = new ArrayList<>();
for(Annotation a:ans)
{
classes.add(a.getClass());
}
//if(classes.contains(Deprecated.class))
{
if (m.getParameterCount()!=0)
{
System.err.println("The method "+m.getName()+" could not be executed as it has parameters. Use a method with example values instead!");
}
else
{
System.out.println("Executing Method: "+m.getName());
long stamp = System.nanoTime();
Object result=m.invoke(c);
long timeconsumed=System.nanoTime()-stamp;
System.out.println("Result of Method: "+result);
System.out.println("Time needed: "+timeconsumed);
}
}
}
}
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
gettimes(EndloseFormel.class);
}
}示例输出:
Executing Method: testmethode
Result of Method: 123
Time needed: 5748https://stackoverflow.com/questions/45051912
复制相似问题