1、参考文档:http://code.google.com/p/javaparser/wiki/UsingThisParser

2、添加maven依赖:

 
    
  1. <repository> 
  2.     <id>javaparserid> 
  3.     <name>JavaParser Repositoryname> 
  4.     <url>http://javaparser.googlecode.com/svn/maven2url> 
  5.     <snapshots> 
  6.         <enabled>falseenabled> 
  7.     snapshots> 
  8. repository> 

 

 
    
  1. <dependency> 
  2.     <groupId>com.google.code.javaparsergroupId> 
  3.     <artifactId>javaparserartifactId> 
  4.     <version>1.0.8version> 
  5. dependency> 

download源代码:

svn checkout http://javaparser.googlecode.com/svn/trunk/ javaparser-read-only

3、常用API的使用

Printing the CompilationUnit to System output

public class CuPrinter {

   
public static void main(String[] args) throws Exception {
       
// creates an input stream for the file to be parsed
       
FileInputStream in = new FileInputStream("test.java");

       
CompilationUnit cu;
       
try {
           
// parse the file
            cu
= JavaParser.parse(in);
       
} finally {
           
in.close();
       
}

       
// prints the resulting compilation unit to default system output
       
System.out.println(cu.toString());
   
}

Visiting class methods

public class MethodPrinter {

   
public static void main(String[] args) throws Exception {
       
// creates an input stream for the file to be parsed
       
FileInputStream in = new FileInputStream("test.java");

       
CompilationUnit cu;
       
try {
           
// parse the file
            cu
= JavaParser.parse(in);
       
} finally {
           
in.close();
       
}

       
// visit and print the methods names
       
new MethodVisitor().visit(cu, null);
   
}

   
/**
     * Simple visitor implementation for visiting MethodDeclaration nodes.
     */

   
private static class MethodVisitor extends VoidVisitorAdapter {

       
@Override
       
public void visit(MethodDeclaration n, Object arg) {
           
// here you can access the attributes of the method.
           
// this method will be called for all methods in this
           
// CompilationUnit, including inner class methods
           
System.out.println(n.getName());
       
}
   
}
}

Changing methods from a class with a visitor

public class MethodChanger {

   
public static void main(String[] args) throws Exception {
       
// creates an input stream for the file to be parsed
       
FileInputStream in = new FileInputStream("test.java");

       
CompilationUnit cu;
       
try {
           
// parse the file
            cu
= JavaParser.parse(in);
       
} finally {
           
in.close();
       
}

       
// visit and change the methods names and parameters
       
new MethodChangerVisitor().visit(cu, null);

       
// prints the changed compilation unit
       
System.out.println(cu.toString());
   
}

   
/**
     * Simple visitor implementation for visiting MethodDeclaration nodes.
     */

   
private static class MethodChangerVisitor extends VoidVisitorAdapter {

       
@Override
       
public void visit(MethodDeclaration n, Object arg) {
           
// change the name of the method to upper case
            n
.setName(n.getName().toUpperCase());

           
// create the new parameter
           
Parameter newArg = ASTHelper.createParameter(ASTHelper.INT_TYPE, "value");

           
// add the parameter to the method
           
ASTHelper.addParameter(n, newArg);
       
}

   
}
}

Changing methods from a class without a visitor

public class MethodChanger {

   
public static void main(String[] args) throws Exception {
       
// creates an input stream for the file to be parsed
       
FileInputStream in = new FileInputStream("test.java");

       
CompilationUnit cu;
       
try {
           
// parse the file
            cu
= JavaParser.parse(in);
       
} finally {
           
in.close();
       
}

       
// change the methods names and parameters
        changeMethods
(cu);

       
// prints the changed compilation unit
       
System.out.println(cu.toString());
   
}

   
private static void changeMethods(CompilationUnit cu) {
       
List<TypeDeclaration> types = cu.getTypes();
       
for (TypeDeclaration type : types) {
           
List<BodyDeclaration> members = type.getMembers();
           
for (BodyDeclaration member : members) {
               
if (member instanceof MethodDeclaration) {
                   
MethodDeclaration method = (MethodDeclaration) member;
                    changeMethod
(method);
               
}
           
}
       
}
   
}

   
private static void changeMethod(MethodDeclaration n) {
       
// change the name of the method to upper case
        n
.setName(n.getName().toUpperCase());

       
// create the new parameter
       
Parameter newArg = ASTHelper.createParameter(ASTHelper.INT_TYPE, "value");

       
// add the parameter to the method
       
ASTHelper.addParameter(n, newArg);
   
}
}

Creating a CompilationUnit from scratch

public class ClassCreator {

   
public static void main(String[] args) throws Exception {
       
// creates the compilation unit
       
CompilationUnit cu = createCU();

       
// prints the created compilation unit
       
System.out.println(cu.toString());
   
}

   
/**
     * creates the compilation unit
     */

   
private static CompilationUnit createCU() {
       
CompilationUnit cu = new CompilationUnit();
       
// set the package
        cu
.setPakage(new PackageDeclaration(ASTHelper.createNameExpr("java.parser.test")));

       
// create the type declaration
       
ClassOrInterfaceDeclaration type = new ClassOrInterfaceDeclaration(ModifierSet.PUBLIC, false, "GeneratedClass");
       
ASTHelper.addTypeDeclaration(cu, type);

       
// create a method
       
MethodDeclaration method = new MethodDeclaration(ModifierSet.PUBLIC, ASTHelper.VOID_TYPE, "main");
        method
.setModifiers(ModifierSet.addModifier(method.getModifiers(), ModifierSet.STATIC));
       
ASTHelper.addMember(type, method);

       
// add a parameter to the method
       
Parameter param = ASTHelper.createParameter(ASTHelper.createReferenceType("String", 0), "args");
        param
.setVarArgs(true);
       
ASTHelper.addParameter(method, param);

       
// add a body to the method
       
BlockStmt block = new BlockStmt();
        method
.setBody(block);

       
// add a statement do the method body
       
NameExpr clazz = new NameExpr("System");
       
FieldAccessExpr field = new FieldAccessExpr(clazz, "out");
       
MethodCallExpr call = new MethodCallExpr(field, "println");
       
ASTHelper.addArgument(call, new StringLiteralExpr("Hello World!"));
       
ASTHelper.addStmt(block, call);

       
return cu;
   
}
}

4、结论:操作相比jdt更加的容易