有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java访问文件并只提取带注释的方法,从而进一步处理它们

我有以下情况:

文件1。java,文件2。JAVA菲伦。爪哇: 我有不同的java文件,有不同的方法method1,method2。。。方法。 现在,这些文件中的一些方法使用annotation@annotated_方法进行了注释

现在我想创建一个java文件,用于访问File1特定目录中的所有文件。java,文件2。JAVA菲伦。java和我只需要对使用@annotated_method annotation注释的方法进行概要分析(或进行一些处理)。必须对每个带注释的方法分别进行分析(或处理该方法)

例如

  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()


共 (1) 个答案

  1. # 1 楼答案

    这可能会帮助您:

    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: 5748