Java海闊天空

          編程是我的生活,但生活不僅僅是編程。

          eclipse插件開(kāi)發(fā):使用AST生成類(源碼)

          本代碼演示如何通過(guò)AST生成一個(gè)完整的類, 最終生成的代碼比較亂, 編譯無(wú)法通過(guò),重點(diǎn)在于對(duì)AST的使用, 無(wú)需考慮最后生成的結(jié)果.

          以下是最終生成的代碼(語(yǔ)法有嚴(yán)重錯(cuò)誤, 請(qǐng)不要計(jì)較這些):
          package com.aptech.lzh;

          import java.util.Date;
          import java.util.Random;

          public class Program {
              
          public static void main(String[] arg) {
                  Program program 
          = new Program();
                  String r 
          = program.getString("中國(guó)");
                  System.out.println(r);
              }


              
          public Program(int a, int[] b, final Integer c) {
                  
          super(null);
              }


              
          public String getString(String p) {
                  String newString 
          = new String("初始值");
                  newString 
          = "你好";
                  String result 
          = newString.indexOf("");
                  newString 
          = name + "你好";
                  
          return newString;
              }


              
          public String isOdd(int a) throws NullPointerException, Exception {
                  
          if (a < 0)
                      
          throw new Exception("數(shù)字不能為負(fù)數(shù)");
                  
          if (a % 2 == 0)
                      
          return "偶數(shù)";
                  
          else {
                      System.out.println(
          "");
                      
          return "奇數(shù)";
                  }

              }

          }


          源代碼:
          package ast.test.demo;

          import org.eclipse.jdt.core.dom.AST;
          import org.eclipse.jdt.core.dom.Assignment;
          import org.eclipse.jdt.core.dom.Block;
          import org.eclipse.jdt.core.dom.ClassInstanceCreation;
          import org.eclipse.jdt.core.dom.CompilationUnit;
          import org.eclipse.jdt.core.dom.ExpressionStatement;
          import org.eclipse.jdt.core.dom.IfStatement;
          import org.eclipse.jdt.core.dom.ImportDeclaration;
          import org.eclipse.jdt.core.dom.InfixExpression;
          import org.eclipse.jdt.core.dom.MethodDeclaration;
          import org.eclipse.jdt.core.dom.MethodInvocation;
          import org.eclipse.jdt.core.dom.Modifier;
          import org.eclipse.jdt.core.dom.NumberLiteral;
          import org.eclipse.jdt.core.dom.PackageDeclaration;
          import org.eclipse.jdt.core.dom.PrimitiveType;
          import org.eclipse.jdt.core.dom.ReturnStatement;
          import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
          import org.eclipse.jdt.core.dom.StringLiteral;
          import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
          import org.eclipse.jdt.core.dom.ThrowStatement;
          import org.eclipse.jdt.core.dom.TypeDeclaration;
          import org.eclipse.jdt.core.dom.TypeLiteral;
          import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
          import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
          import org.eclipse.jdt.core.dom.Assignment.Operator;
          import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;

          public class Demo {
              
          public static void main(String[] args) {
                  AST ast 
          = AST.newAST(AST.JLS3);
                  CompilationUnit compilationUnit 
          = ast.newCompilationUnit();
                  
                  
          //創(chuàng)建類
                  TypeDeclaration programClass = ast.newTypeDeclaration();
                  programClass.setName(ast.newSimpleName(
          "Program"));
                  programClass.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
                  compilationUnit.types().add(programClass);

                  
          //創(chuàng)建包
                  PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
                  packageDeclaration.setName(ast.newName(
          "com.aptech.lzh"));
                  compilationUnit.setPackage(packageDeclaration);
                  
                  
          //要導(dǎo)入的包
                  String[] imports = {"java.util.Date""java.util.Random"};
                  
          for(String imp : imports){
                      ImportDeclaration importDeclaration 
          = ast.newImportDeclaration();
                      importDeclaration.setName(ast.newName(imp));
                      compilationUnit.imports().add(importDeclaration);
                  }

                  
                  
          //創(chuàng)建一個(gè)main方法
                  {
                      MethodDeclaration main 
          = ast.newMethodDeclaration();
                      main.setName(ast.newSimpleName(
          "main"));
                      main.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
                      main.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
                      main.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID));
                      programClass.bodyDeclarations().add(main);
                      Block mainBlock 
          = ast.newBlock();
                      main.setBody(mainBlock);
                      
                      
          //給main方法定義String[]參數(shù)
                      SingleVariableDeclaration mainParameter = ast.newSingleVariableDeclaration();
                      mainParameter.setName(ast.newSimpleName(
          "arg"));
                      mainParameter.setType(ast.newArrayType(ast.newSimpleType(ast.newName(
          "String"))));
                      main.parameters().add(mainParameter);
                      
                      
          //創(chuàng)建Pragram對(duì)象: Program program=new Program();
                      VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
                      fragment.setName(ast.newSimpleName(
          "program"));
                      VariableDeclarationStatement statement 
          = ast.newVariableDeclarationStatement(fragment);
                      statement.setType(ast.newSimpleType(ast.newSimpleName(
          "Program")));
                      
                      ClassInstanceCreation classInstanceCreation 
          = ast.newClassInstanceCreation();
                      classInstanceCreation.setType(ast.newSimpleType(ast.newSimpleName(
          "Program")));
                      
                      fragment.setInitializer(classInstanceCreation);
                      
                      mainBlock.statements().add(statement);
                      
                      
          //調(diào)用getString方法:String r = program.getString("中國(guó)");
                      MethodInvocation methodInvocation = ast.newMethodInvocation();
                      methodInvocation.setExpression(ast.newSimpleName(
          "program"));
                      methodInvocation.setName(ast.newSimpleName(
          "getString"));
                      
                      
          //String參數(shù)
                      StringLiteral stringLiteral = ast.newStringLiteral();
                      stringLiteral.setLiteralValue(
          "中國(guó)");
                      methodInvocation.arguments().add(stringLiteral);
                      
                      
          //創(chuàng)建變量
                      VariableDeclarationFragment fragment2 = ast.newVariableDeclarationFragment();
                      fragment2.setName(ast.newSimpleName(
          "r"));
                      VariableDeclarationStatement statement3 
          = ast.newVariableDeclarationStatement(fragment2);
                      statement3.setType(ast.newSimpleType(ast.newSimpleName(
          "String")));
                      fragment2.setInitializer(methodInvocation);
                      
                      mainBlock.statements().add(statement3);
                      
                      
                      
          //輸出r的值: System.out.println(r);
                      MethodInvocation methodInvocation2 = ast.newMethodInvocation();
                      methodInvocation2.setExpression(ast.newName(
          "System.out"));
                      methodInvocation2.setName(ast.newSimpleName(
          "println"));
                      methodInvocation2.arguments().add(ast.newSimpleName(
          "r"));
                      ExpressionStatement statement2 
          = ast.newExpressionStatement(methodInvocation2);
                      
                      mainBlock.statements().add(statement2);
                  }

                  
                  
          //構(gòu)造方法
                  {
                      MethodDeclaration constructorMethod 
          = ast.newMethodDeclaration();
                      constructorMethod.setConstructor(
          true);
                      constructorMethod.setName(ast.newSimpleName(
          "Program"));
                      constructorMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
                      
          {
                          
          //基本類型的參數(shù)
                          SingleVariableDeclaration p1 = ast.newSingleVariableDeclaration();
                          p1.setName(ast.newSimpleName(
          "a"));
                          p1.setType(ast.newPrimitiveType(PrimitiveType.INT));
                          
                          
          //int[]類型的參數(shù)
                          SingleVariableDeclaration p2 = ast.newSingleVariableDeclaration();
                          p2.setName(ast.newSimpleName(
          "b"));
                          p2.setType(ast.newArrayType(ast.newPrimitiveType(PrimitiveType.INT)));
                          
                          
          //引用類型的參數(shù)
                          SingleVariableDeclaration p3 = ast.newSingleVariableDeclaration();
                          p3.setName(ast.newSimpleName(
          "c"));
                          p3.setType(ast.newSimpleType(ast.newName(
          "Integer")));
                          p3.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
                          
                          constructorMethod.parameters().add(p1);
                          constructorMethod.parameters().add(p2);
                          constructorMethod.parameters().add(p3);
                      }

                      
                      Block constructBlock 
          = ast.newBlock();
                      constructorMethod.setBody(constructBlock);
                      
                      programClass.bodyDeclarations().add(constructorMethod);
                      
                      SuperConstructorInvocation superConstructorInvocation 
          = ast.newSuperConstructorInvocation();
                      constructBlock.statements().add(superConstructorInvocation);
                      superConstructorInvocation.arguments().add(ast.newNullLiteral());
                  }

                  
                  
          /*定義一個(gè)方法,形如:
                  public String getString(String name){
                      String newString = name + "你好";
                      return newString;
                  }
                  
          */

                  
                  
          {
                      MethodDeclaration getString 
          = ast.newMethodDeclaration();
                      getString.setName(ast.newSimpleName(
          "getString"));
                      getString.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
                      SingleVariableDeclaration p 
          = ast.newSingleVariableDeclaration();
                      p.setName(ast.newSimpleName(
          "p"));
                      p.setType(ast.newSimpleType(ast.newName(
          "String")));
                      getString.parameters().add(p);
                      getString.setReturnType2(ast.newSimpleType(ast.newSimpleName(
          "String")));
                      
                      
                      
          //創(chuàng)建塊
                      Block block = ast.newBlock();
                      getString.setBody(block);
                      programClass.bodyDeclarations().add(getString);
                      
                      
          //方法內(nèi)容----定義String變量
                      VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
                      fragment.setName(ast.newSimpleName(
          "newString"));
                      VariableDeclarationStatement statement 
          = ast.newVariableDeclarationStatement(fragment);
                      
                      
          //String newString = "初始值";
                      /*StringLiteral stringLiteral2 = ast.newStringLiteral();
                      stringLiteral2.setLiteralValue("初始值");
                      fragment.setInitializer(stringLiteral2);
          */

                      
                      ClassInstanceCreation classInstanceCreation 
          = ast.newClassInstanceCreation();
                      classInstanceCreation.setType(ast.newSimpleType(ast.newName(
          "String")));
                      SingleVariableDeclaration p1 
          = ast.newSingleVariableDeclaration();
                      StringLiteral stringLiteral3 
          = ast.newStringLiteral();
                      stringLiteral3.setLiteralValue(
          "初始值");
                      classInstanceCreation.arguments().add(stringLiteral3);
                      fragment.setInitializer(classInstanceCreation);
                      
                      statement.setType(ast.newSimpleType(ast.newName(
          "String")));
                      
                      Assignment assignment 
          = ast.newAssignment();
                      assignment.setLeftHandSide(ast.newSimpleName(
          "newString"));
                      StringLiteral stringLiteral 
          = ast.newStringLiteral();
                      stringLiteral.setLiteralValue(
          "你好");
                      
                      assignment.setRightHandSide(stringLiteral);
                      assignment.setOperator(Operator.ASSIGN);
                      ExpressionStatement statement2 
          = ast.newExpressionStatement(assignment);
                      
                      block.statements().add(statement);
                      block.statements().add(statement2);
                      
                      
          //方法調(diào)用
                      MethodInvocation methodInvocation = ast.newMethodInvocation();
                      methodInvocation.setExpression(ast.newName(
          "newString"));
                      methodInvocation.setName(ast.newSimpleName(
          "index")); //方法名
                      StringLiteral stringLiteral2 = ast.newStringLiteral();
                      stringLiteral2.setLiteralValue(
          "");
                      methodInvocation.arguments().add(stringLiteral2);
                      
                      VariableDeclarationFragment fragment2 
          = ast.newVariableDeclarationFragment();
                      fragment2.setInitializer(methodInvocation);
                      fragment2.setName(ast.newSimpleName(
          "result"));
                      VariableDeclarationStatement statement3 
          = ast.newVariableDeclarationStatement(fragment2);
                      statement3.setType(ast.newSimpleType(ast.newName(
          "String")));
                      
                      block.statements().add(statement3);
                      
                      StringLiteral stringLiteral4 
          = ast.newStringLiteral();
                      stringLiteral4.setLiteralValue(
          "你好");
                      
                      InfixExpression infixExpression 
          = ast.newInfixExpression();
                      infixExpression.setLeftOperand(ast.newName(
          "name"));
                      infixExpression.setOperator(org.eclipse.jdt.core.dom.InfixExpression.Operator.PLUS);
                      infixExpression.setRightOperand(stringLiteral4);
                      
                      Assignment assignment2 
          = ast.newAssignment();
                      assignment2.setLeftHandSide(ast.newSimpleName(
          "newString"));
                      assignment2.setOperator(Operator.ASSIGN);
                      assignment2.setRightHandSide(infixExpression);
                      
                      ExpressionStatement statement4 
          = ast.newExpressionStatement(assignment2);
                      
                      block.statements().add(statement4);

                      ReturnStatement rs 
          = ast.newReturnStatement();
                      rs.setExpression(ast.newName(
          "newString"));
                      block.statements().add(rs);
                  }

                  
                  
          /**
                   * 定義一個(gè)方法,形如:
                   * public String isOdd(int a) throws NullPointerException, Exception{
                   *     if(a < 0) throw new Exception("數(shù)字不能為負(fù)數(shù)");
                   * 
                   *     if(a % 2 == 0){
                   *         return "偶數(shù)";
                   *     }else{
                   *         System.out.println("完");
                   *         return "奇數(shù)";
                   *     }
                   
          */

                  
          {
                      MethodDeclaration methodDeclaration 
          = ast.newMethodDeclaration();
                      methodDeclaration.setName(ast.newSimpleName(
          "isOdd"));
                      methodDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
                      methodDeclaration.setReturnType2(ast.newSimpleType(ast.newSimpleName(
          "String")));
                      
          //設(shè)置參數(shù)
                      SingleVariableDeclaration singleVariableDeclaration = ast.newSingleVariableDeclaration();
                      singleVariableDeclaration.setName(ast.newSimpleName(
          "a"));
                      singleVariableDeclaration.setType(ast.newPrimitiveType(PrimitiveType.INT));
                      methodDeclaration.parameters().add(singleVariableDeclaration);

                      
          //拋出異常
                      methodDeclaration.thrownExceptions().add(ast.newSimpleName("NullPointerException"));
                      methodDeclaration.thrownExceptions().add(ast.newSimpleName(
          "Exception"));
                      
                      
          //創(chuàng)建塊{}
                      Block isOddBlock = ast.newBlock();
                      methodDeclaration.setBody(isOddBlock);
                      
                      
          //創(chuàng)建if與異常
                      IfStatement ifStatement = ast.newIfStatement();
                      
          //表達(dá)式 a < 0
                      InfixExpression infixExpression = ast.newInfixExpression();
                      infixExpression.setLeftOperand(ast.newSimpleName(
          "a"));
                      infixExpression.setOperator(org.eclipse.jdt.core.dom.InfixExpression.Operator.LESS);
                      
                      NumberLiteral numberLiteral 
          = ast.newNumberLiteral("0");
                      infixExpression.setRightOperand(numberLiteral);
                      
                      ifStatement.setExpression(infixExpression);
                      
                      
          //設(shè)置if中的內(nèi)容
                      ThrowStatement throwStatement = ast.newThrowStatement();
                      ClassInstanceCreation classInstanceCreation 
          = ast.newClassInstanceCreation();
                      classInstanceCreation.setType(ast.newSimpleType(ast.newSimpleName(
          "Exception")));
                      StringLiteral stringLiteral 
          = ast.newStringLiteral();
                      stringLiteral.setLiteralValue(
          "數(shù)字不能為負(fù)數(shù)");
                      classInstanceCreation.arguments().add(stringLiteral);
                      throwStatement.setExpression(classInstanceCreation);
                      ifStatement.setThenStatement(throwStatement);
                      
                      
          //if(a % 2 == 0)
                      IfStatement ifStatement2 = ast.newIfStatement();
                      InfixExpression infixExpression2 
          = ast.newInfixExpression();
                      infixExpression2.setLeftOperand(ast.newSimpleName(
          "a"));
                      infixExpression2.setOperator(org.eclipse.jdt.core.dom.InfixExpression.Operator.REMAINDER);
                      NumberLiteral numberLiteral2 
          = ast.newNumberLiteral("2");
                      infixExpression2.setRightOperand(numberLiteral2);
                      
                      InfixExpression infixExpression3 
          = ast.newInfixExpression();
                      infixExpression3.setLeftOperand(infixExpression2);
                      infixExpression3.setOperator(org.eclipse.jdt.core.dom.InfixExpression.Operator.EQUALS);
                      NumberLiteral numberLiteral3 
          = ast.newNumberLiteral("0");
                      infixExpression3.setRightOperand(numberLiteral3);
                      
                      ifStatement2.setExpression(infixExpression3);
                      
                      
          //return "偶數(shù)";
                      ReturnStatement returnStatement = ast.newReturnStatement();
                      StringLiteral stringLiteral2 
          = ast.newStringLiteral();
                      stringLiteral2.setLiteralValue(
          "偶數(shù)");
                      returnStatement.setExpression(stringLiteral2);
                      ifStatement2.setThenStatement(returnStatement);
                      
                      
          //else
                      Block elseBlock = ast.newBlock();
                      MethodInvocation methodInvocation 
          = ast.newMethodInvocation();
                      methodInvocation.setExpression(ast.newName(
          "System.out"));
                      methodInvocation.setName(ast.newSimpleName(
          "println"));
                      StringLiteral stringLiteral4 
          = ast.newStringLiteral();
                      stringLiteral4.setLiteralValue(
          "");
                      methodInvocation.arguments().add(stringLiteral4);
                      ExpressionStatement statement 
          = ast.newExpressionStatement(methodInvocation);
                      elseBlock.statements().add(statement);
                      
                      ReturnStatement returnStatement2 
          = ast.newReturnStatement();
                      StringLiteral stringLiteral3 
          = ast.newStringLiteral();
                      stringLiteral3.setLiteralValue(
          "奇數(shù)");
                      returnStatement2.setExpression(stringLiteral3);
                      elseBlock.statements().add(returnStatement2);
                      
                      ifStatement2.setElseStatement(elseBlock);
                      
                      isOddBlock.statements().add(ifStatement);
                      isOddBlock.statements().add(ifStatement2);
                      programClass.bodyDeclarations().add(methodDeclaration);
                  }

                  
                  System.out.println(compilationUnit.toString());
                  
              }

          }

          posted on 2010-02-12 01:56 李贊紅 閱讀(3013) 評(píng)論(0)  編輯  收藏


          只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           

          導(dǎo)航

          <2010年2月>
          31123456
          78910111213
          14151617181920
          21222324252627
          28123456
          78910111213

          統(tǒng)計(jì)

          常用鏈接

          留言簿(12)

          隨筆檔案(28)

          相冊(cè)

          技術(shù)友情博客

          搜索

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          主站蜘蛛池模板: 大理市| 富阳市| 浙江省| 监利县| 措美县| 临桂县| 正蓝旗| 松潘县| 健康| 抚州市| 高州市| 鄂托克旗| 综艺| 建德市| 微山县| 商水县| 孝感市| 崇阳县| 凤山县| 冕宁县| 昭觉县| 仙桃市| 襄城县| 大庆市| 杨浦区| 白水县| 运城市| 武隆县| 蒙自县| 纳雍县| 明溪县| 鸡西市| 边坝县| 桃源县| 永年县| 阜南县| 苍梧县| 荃湾区| 凤台县| 乐昌市| 洛川县|