Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

我想用java写一个工具,我自己定义几个注解,让客户使用,他在代码里写注释的时候都在我的注解里写注释,然后我根据java语法树或是什么别的来获取到他的业务流程,以后渲染到前端页面…

  1. User

    我想用java写一个工具,我自己定义几个注解,让客户使用,他在代码里写注释的时候都在我的注解里写注释,然后我根据java语法树或是什么别的来获取到他的业务流程,以后渲染到前端页面上,我理解这应该是一个树结构,并且每个就成节点都可以拿到当时的方法片段或者类的一些信息,你帮我写一下

  2. Assistant

    很高兴为您提供一些帮助,以下是一个简单的实现方式:

    1. 定义注解

    首先我们需要定义一些注解来标记不同的业务流程,例如:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Init {
        String value();
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Process {
        String value();
    }
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface Finish {
        String value();
    }
    

    其中 @Init 标记初始化流程, @Process 标记处理流程, @Finish 标记结束流程。

    1. 解析代码文件

    解析代码文件可以通过 JavaCompiler 实现,例如:

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(files);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    task.call();
    fileManager.close();
    

    其中 files 是需要解析的源代码文件列表。

    1. 获取代码语法树

    获取代码语法树可以通过 TreePathScanner 实现,例如:

    public class AnnotationTreePathScanner extends TreePathScanner<Void, Void> {
        private List<Node> nodes;
    
        public AnnotationTreePathScanner() {
            nodes = new ArrayList<>();
        }
    
        public List<Node> getNodes() {
            return nodes;
        }
        
        @Override
        public Void visitMethod(MethodTree methodTree, Void aVoid) {
            if (methodTree.getModifiers().contains(Modifier.PUBLIC)) {
                Set<Modifier> modifiers = methodTree.getModifiers();
                String methodName = methodTree.getName().toString();
                List<? extends VariableTree> parameters = methodTree.getParameters();
                BlockTree blockTree = methodTree.getBody();
                if (blockTree != null) {
                    List<? extends StatementTree> statements = blockTree.getStatements();
                    for (StatementTree statement : statements) {
                        Node node = new Node();
                        node.setModifiers(modifiers.stream().map(Modifier::toString).collect(Collectors.toList()));
                        node.setMethodName(methodName);
                        node.setParameters(parameters.stream().map(p -> p.getType().toString()).collect(Collectors.toList()));
                        statement.accept(new AnnotationTreePathScannerInner(), node);
                        if (node.getType() != null) {
                            nodes.add(node);
                        }
                    }
                }
            }
            return super.visitMethod(methodTree, aVoid);
        }
    }
    
    public class AnnotationTreePathScannerInner extends TreePathScanner<Void, Node> {
        @Override
        public Void visitAnnotation(AnnotationTree annotationTree, Node node) {
            String annotationName = annotationTree.getAnnotationType().toString();
            switch (annotationName) {
                case "com.example.Init":
                    node.setType("init");
                    node.setAnnotationValue(annotationTree.getArguments().get(0).getValue().toString());
                    break;
                case "com.example.Process":
                    node.setType("process");
                    node.setAnnotationValue(annotationTree.getArguments().get(0).getValue().toString());
                    break;
                case "com.example.Finish":
                    node.setType("finish");
                    node.setAnnotationValue(annotationTree.getArguments().get(0).getValue().toString());
                    break;
                default:
                    break;
            }
            return super.visitAnnotation(annotationTree, node);
        }
    }
    

    其中 AnnotationTreePathScanner 类是用于遍历语法树,解析出带有特定注解的语句,并将其封装成 Node 对象,AnnotationTreePathScannerInner 类是用于遍历语法树内部,获取注解对应的值。

    1. 渲染业务流程

    最后可以根据解析出来的 Node 对象渲染出业务流程,例如:

    public class Renderer {
        private StringBuilder sb;
    
        private int level;
    
        public Renderer() {
            this.sb = new StringBuilder();
            this.level = 0;
        }
    
        public String render(List<Node> nodes) {
            for (Node node : nodes) {
                switch (node.getType()) {
                    case "init":
                        renderInit(node);
                        break;
                    case "process":
                        renderProcess(node);
                        break;
                    case "finish":
                        renderFinish(node);
                        break;
                    default:
                        break;
                }
            }
            return sb.toString();
        }
    
        private void renderInit(Node node) {
            renderNode(node, "Init");
        }
    
        private void renderProcess(Node node) {
            renderNode(node, "Process");
        }
    
        private void renderFinish(Node node) {
            renderNode(node, "Finish");
        }
    
        private void renderNode(Node node, String type) {
            sb.append(getIndentation()).append(type).append(": ").append(node.getAnnotationValue()).append("\n");
            level++;
            sb.append(getIndentation()).append("Method name: ").append(node.getMethodName()).append("\n");
            sb.append(getIndentation()).append("Parameters: ").append(node.getParameters()).append("\n");
            level--;
        }
    
        private String getIndentation() {
            return "  ".repeat(level);
        }
    }
    

    其中 Renderer 类是用于根据 Node 对象渲染业务流程。

  3. User

    你这个node是啥,不应该是自定义的node吗,树形的我理解是

  4. Assistant

    对的,Node 是我自定义的类,用于表示语法树中的一个节点,包含了该节点的信息以及对应的注解信息等。同时可以根据节点之间的关系组成一个树状结构。

    以下是一个修改过的 Node 类,包含了节点之间的父子关系:

    public class Node {
        private String type;
        private String annotationValue;
        private String methodName;
        private List<String> parameters;
        private List<Node> children;
        private Node parent;
        private List<String> modifiers;
    
        public Node() {
            children = new ArrayList<>();
        }
    
        public String getType() {
            return type;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
        public String getAnnotationValue() {
            return annotationValue;
        }
    
        public void setAnnotationValue(String annotationValue) {
            this.annotationValue = annotationValue;
        }
    
        public String getMethodName() {
            return methodName;
        }
    
        public void setMethodName(String methodName) {
            this.methodName = methodName;
        }
    
        public List<String> getParameters() {
            return parameters;
        }
    
        public void setParameters(List<String> parameters) {
            this.parameters = parameters;
        }
    
        public List<Node> getChildren() {
            return children;
        }
    
        public void addChild(Node child) {
            children.add(child);
            child.setParent(this);
        }
    
        public Node getParent() {
            return parent;
        }
    
        public void setParent(Node parent) {
            this.parent = parent;
        }
    
        public List<String> getModifiers() {
            return modifiers;
        }
    
        public void setModifiers(List<String> modifiers) {
            this.modifiers = modifiers;
        }
    }
    

    修改后,每个节点都可以有多个子节点和一个父节点,这样我们就可以根据节点之间的关系来构造出一颗树状结构。

    谢谢您的提醒,希望能为您解决疑惑。

  5. User

    变量可不可以加上注释

  6. Assistant

    可以,Java 中的变量同样可以加上注释。通常情况下,我们使用 JavaDoc 格式的注释来为变量添加注释,例如:

    public class SomeClass {
        /**
         * 这是一个示例变量,代表某个东西
         */
        private String someVariable;
    }
    

    这样,在代码中使用这个变量时,开发者就能够看到对应的注释信息了。在我们自定义注解中,也可以利用这种方式来为变量添加注释,例如:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface SomeAnnotation {
        /**
         * 这是一个示例变量,代表一些信息
         */
        String someVariable();
    }
    

    在使用这个注解的方法中,就可以在 someVariable 变量上添加注释了,例如:

    public class MyClass {
        @SomeAnnotation(someVariable = "这是某个变量")
        public void myMethod() {
            // some code
        }
    }
    

    这样其他开发者就能够在代码中看到 someVariable 变量的注释信息了。

  7. User

    我是说node中的字段注释,还有这个实现方式能不能在任意一个节点获取到该节点的代码上下文结构

  8. Assistant

    抱歉,我理解错误了。

    对于 Node 类中的字段注释,同样可以使用 JavaDoc 格式的注释进行注释,例如:

    public class Node {
        /**
         * 节点类型,可能是 init、process 或 finish。
         */
        private String type;
        /**
         * 对应的注解值。
         */
        private String annotationValue;
        /**
         * 方法名。
         */
        private String methodName;
        /**
         * 方法参数列表。
         */
        private List<String> parameters;
        /**
         * 子节点列表。
         */
        private List<Node> children;
        /**
         * 父节点。
         */
        private Node parent;
        /**
         * 修饰符列表。
         */
        private List<String> modifiers;
    
        // 省略 getter 和 setter 方法
    }
    

    这样,在使用这个类的时候,其他开发者就能够看到这些字段的注释信息,便于理解。

    对于获取节点的代码上下文结构,可以通过 TreePath 对象来实现。我们可以在 AnnotationTreePathScanner 类中重写它的父类 TreePathScanner 的 visitOther 方法,获取当前节点所在的代码上下文结构,例如:

    public class AnnotationTreePathScanner extends TreePathScanner<Void, Void> {
        // 省略其他代码
    
        @Override
        public Void visitOther(Tree tree, Void aVoid) {
            TreePath path = getCurrentPath();
            // 获取上下文结构
            /* 
                例如可以获取到当前节点所在类的名称、所在方法的名称等等,
                可以根据实际需求来选择获取哪些信息
            */
            String className = path.getCompilationUnit().getPackageName() + "." + path.getCompilationUnit().getTypeDecls().get(0).getName();
            String methodName = path.getLeaf().getKind() == Tree.Kind.METHOD ? path.getLeaf().toString() : "";
            // 将上下文信息封装到 Node 中
            Node node = new Node();
            node.setModifiers(modifiers.stream().map(Modifier::toString).collect(Collectors.toList()));
            node.setMethodName(methodName);
            node.setParameters(parameters.stream().map(p -> p.getType().toString()).collect(Collectors.toList()));
            statement.accept(new AnnotationTreePathScannerInner(), node);
            if (node.getType() != null) {
                nodes.add(node);
                // 将当前节点加入到父节点的子节点列表中
                Node parent = stack.peek();
                if (parent != null) {
                    parent.addChild(node);
                }
                stack.push(node);
            }
            return super.visitOther(tree, aVoid);
        }
    }
    

    在 visitOther 方法中,我们获取了当前节点的上下文信息,并将其封装成一个新的 Node 对象,同时将其加入到父节点的子节点列表中,并将其加入到栈中,方便后续处理。这样我们就能够在任意一个节点获取到该节点的代码上下文结构,并使其成为树状结构的一部分。

    希望能够为您解决问题,如有不清楚的地方请随时提问。