首页 > 编程知识 正文

java compare方法,注解 java

时间:2023-05-04 02:02:19 阅读:114806 作者:4100

Javaparser使用、转换什么是Javaparser分析并生成Java代码。

Javaparser库提供了Java代码的抽象语法树“abstract syntax树”。

通过AST结构,可以用简单的编程方法使用Java代码。

为什么antlr4需要Javaparser? Javaparser提供了更多的API,可以专门处理Java文件,使用起来更轻松。

1 .分析多个Java文件/***分析项目下的所有Java文件** @param path项目根*/publicstaticvoidparseproject (string path ) path rrath onlyparsingprojectrootprojectroot=newparsercollectionstrategy ().collect ) root; 项目根. getsourceroots (.foreach ) sourceroot-{system.out.println ) sourceroot ); try {//sourcerootsourceroot.try to parse (; }catch(ioexceptione ) { e.printStackTrace ); //获取分析后编译的设备列表listcompilationunitculist=source root.getcompilationunits (; Cu list.foreach (javaparserutil :3360 parseonefile; ); }/***分析单个Java文件** @param cu编译单元*/publicstaticvoidparseonefile (compilationunitcu ) /类型声明nodelistypedeclarationunefile types=cu.getTypes (; 类型描述(for )? type : types (system.out.println ) ' #'type.getname ); //成员NodeListBodyDeclaration? members=type.getMembers (; members.foreach (javaparserutil :3360 process node; (}}/***处理类型、方法、成员* * @ param node */publicstaticvoidprocessnode (node ) if ) nodeInstanceoftypedeclaration )//else if (nodeinstanceofmethoddeclaration )//方法声明/osomethingwiththismethoddeclarationstringmethoddname=(方法描述性描述) 系统. out.println (方法: ) methodname ); } else if (nodeinstanceoffielddeclaration (/成员变量声明//dosomethingwiththisfielddeclaration//)注释comment comment=node simplenamefieldname=variables.get (0).getName ); if (注释!=null (system.out.print (handle comment ) comment.getcontent ) ); }system.out.print (() () () () () ) ) ); 系统. out.print (field name ); System.out.println (; } for (node child : node.get child n

odes()) { processNode(child); }} 2.修改Java文件 public static void main(String[] args) throws FileNotFoundException { // The directory where we store the examples String pathToExamplesDir = "." + separator + "src" + separator + "main" + separator + "resources"; String javaName = pathToExamplesDir + separator + "ASimpleClass.java"; // Parse the code of an entire source file, tzdl Compilation Unit CompilationUnit compilationUnitNode = StaticJavaParser.parse(new File(MyJavaParserConstant.JAVA_FILE_PATH)); printCompilationUnit("My original class", compilationUnitNode); // Modifying the name of the class String className = "HelloWorld"; compilationUnitNode.getClassByName(className).get() .setName("MyRenamedClass"); printCompilationUnit("Renamed class", compilationUnitNode); // Adding a method: we add a setter MethodDeclaration setter = compilationUnitNode .getClassByName("MyRenamedClass").get() .addMethod("setAField", Modifier.Keyword.PUBLIC); setter.addParameter("boolean", "aField"); setter.getBody().get().getStatements().add(new ExpressionStmt( new AssignExpr( new FieldAccessExpr(new ThisExpr(),"aField"), new NameExpr("aField"), AssignExpr.Operator.ASSIGN ))); printCompilationUnit("With a setter", compilationUnitNode);} 3.生成Java代码 /** * 代码生成 * * @author zhangcheng * @date 2021/12/4 */public class CodeGenerationExample { public static void main(String[] args) { CompilationUnit compilationUnit = new CompilationUnit(); compilationUnit.setPackageDeclaration("my.example.javaparser"); // Add an asterisk import for java.util compilationUnit.addImport("java.util", false, true); // Create a class (not an interface, so the 2nd parameter is false) ClassOrInterfaceDeclaration myClass = compilationUnit.addClass("MyClass", Modifier.Keyword.PUBLIC); myClass.addField("List<String>", "elements", Modifier.Keyword.PRIVATE); // Method to add an element to the field MethodDeclaration addElement = myClass.addMethod("addElement", Modifier.Keyword.PUBLIC); // our method get a parameter: the value to add to the field addElement.addParameter("String", "newElement"); // the body consists in one expression wrapped into a statement // the expression is in invocation of elements.add to which we // pass the parameter addElement.getBody().get().getStatements().add(new ExpressionStmt( new MethodCallExpr(new NameExpr("elements"), new SimpleName("add"), NodeList.nodeList(new NameExpr("newElement"))) )); // Method to get elements MethodDeclaration getElements = myClass.addMethod("getElements", Modifier.Keyword.PUBLIC); // we specify that we are returning a Collection of String getElements.setType("Collection<String>"); // The body consists of just a return statement. We return the // field getElements.getBody().get().getStatements().add(new ReturnStmt( new NameExpr("elements"))); System.out.println(compilationUnit); }} 参考

Javaparser github

Javaparser homepage

Javaparser使用教程

Javaparser代码生成

https://github.com/ftomassetti/effectivejava.git

https://github.com/javaparser/javasymbolsolver.git

可用的demos
https://github.com/ftomassetti/analyze-java-code-examples.git

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。