取得java项目,并且在某个方法中添加内容

获得java项目,并且在某个方法中添加内容

获得工作区的第一个项目,找到类“x.y.z.Test”,并且在方法中添加一段代码

eg:

 

public static void doS() {
  IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
        System.out.println(projects.length);
        if (projects.length == 0) {
         return;
        }
        IProject project = projects[0];
        System.out.println();
        IJavaProject jp = JavaCore.create(project);

        try {
         IType tp = jp.findType("x.y.z.Test");
         ICompilationUnit cu = tp.getCompilationUnit();
   File file = cu.getResource().getLocation().toFile();
   Document doc = new Document(getFileAsString(file));

   ASTParser parsert = ASTParser.newParser(AST.JLS3);
   parsert.setSource(doc.get().toCharArray());
   System.out.println("!!!!!!!!!!---1---" + doc.getLength());
   CompilationUnit result = (CompilationUnit) parsert.createAST(null);
   result.recordModifications();   

   
   AST ast = result.getAST();
   
   List types = result.types();
   TypeDeclaration typeDec = (TypeDeclaration) types.get(0);

   List importList = result.imports();
   PackageDeclaration packetDec = result.getPackage();
   String className = typeDec.getName().toString();
   MethodDeclaration methodDec[] = typeDec.getMethods();
   FieldDeclaration fieldDec[] = typeDec.getFields();
   
   System.out.println("包:");
   System.out.println(packetDec.getName());
   System.out.println("引用import:");
   for (Object obj : importList) {
       ImportDeclaration importDec = (ImportDeclaration) obj;
       System.out.println(importDec.getName());
   }
   
   System.out.println("类:");
   System.out.println(className);
   System.out.println("========================");
   System.out.println("函数:");
   for (MethodDeclaration method : methodDec) {
    System.out.println("=============");
    System.out.println(method);
    List lst = method.getBody().statements();
    
    MethodInvocation mi = ast.newMethodInvocation();
    mi.setName(ast.newSimpleName("setLayout")); 
       mi.arguments().add(ast.newSimpleName("gridLayout"));
       lst.add(ast.newExpressionStatement(mi));
      
       Assignment assign = ast.newAssignment();

       assign.setLeftHandSide(ast.newSimpleName("i"));

       assign.setOperator(Assignment.Operator.ASSIGN);

       assign.setRightHandSide(ast.newNumberLiteral("5"));

       ExpressionStatement statement = ast.newExpressionStatement(assign);
       lst.add(statement); // 可以追加到指定位置
       
       Map<String, String> options = new HashMap<String, String>();
    options.put(
      DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH,
      "true");
    
    TextEdit edits = result.rewrite(doc, options);
    edits.apply(doc);
    string2File(doc.get(), file);
    cu.getResource().refreshLocal(0, null);
    break;
   }
   
   System.out.println("变量:");
   for (FieldDeclaration fieldDecEle : fieldDec) {
       //public static 
       for (Object modifiObj : fieldDecEle.modifiers()) {
           Modifier modify = (Modifier) modifiObj;
           System.out.print(modify + "-");
       }
       System.out.println(fieldDecEle.getType());
       for (Object obj : fieldDecEle.fragments()) {
           VariableDeclarationFragment frag = (VariableDeclarationFragment) obj;
           System.out.println("[FIELD_NAME:]" + frag.getName());
       }
   }
   
        } catch (Exception e) {
         e.printStackTrace();
        }
       
 }

 
 public static String getFileAsString(File file) throws IOException {
  BufferedReader in = new BufferedReader(new FileReader(file));
  StringBuffer buffer = new StringBuffer();
  String line = null;
  // iterator read line
  while (null != (line = in.readLine())) {
   buffer.append(line);
   buffer.append("\n");
  }
  return buffer.toString();
 }
 
 public static void string2File(String content, File file) throws IOException {
  // create file if it necessary
  if (!file.exists()) {
   file.createNewFile();
  }
  // write to file
  FileWriter fw = new FileWriter(file);
  fw.write(content);
  fw.flush();
 }