javaparser试用

 

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

2、添加maven依赖:

 
 
  1. <repository> 
  2.     <id>javaparser</id> 
  3.     <name>JavaParser Repository</name> 
  4.     <url>http://javaparser.googlecode.com/svn/maven2</url> 
  5.     <snapshots> 
  6.         <enabled>false</enabled> 
  7.     </snapshots> 
  8. </repository> 

 

 
 
  1. <dependency> 
  2.     <groupId>com.google.code.javaparser</groupId> 
  3.     <artifactId>javaparser</artifactId> 
  4.     <version>1.0.8</version> 
  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更加的容易

 


http://tianya23.blog.51cto.com/1081650/617244

java精神(基于函数式组合子逻辑的javaparser框架) 一。 释名。 为什么叫精神? 如果你熟悉c++,那么你可能知道一个叫做”spirit”的parser库。它利用c++的模板元编程能力,使用c++语言本身提供了一个递归下降文法解析的框架。 我这里介绍的jparsec库,就是一个java里面的递归下降文法解析框架。 不过,它并非是spirit的java版本。 Jparsec的蓝本来自Haskell语言的parsec库。Parsec是一个基于monad的parser组合子库。 这个库的目的是要在java中提供一个类似parsec, spirit的库,这种组合子库并非c++的专利,java/c#也可以做到。这个库还将在java5.0上被改写,类型安全上它将也不再逊色于c++。 那么,为什么叫“函数式”呢?java是面向对象的嘛。 如果你使用过haskell, lisp等语言,这个函数式不用解释你也知道是怎么回事了。 如果你是一个老牌的c++/java程序员,那么这里还要稍微解释一下。当然如果您对这些虚头八脑的名词不感兴趣,那么,你尽可以跳过这一章,不知道什么是“函数式”,并不会影响你对这个库的理解的。 C++这几年随着gp的普及,“函数式”这个老孔乙己逐渐又被人从角落里面拽了出来。一个c++程序员所熟悉的“函数式”很可能是stl的for_each, transform,count_if这些函数。 怎么说呢,就象我不能否定str.length()这个调用属于OO一样,我也无法说for_each, transform不是函数式。 但是,“函数式”的精髓不在于此。 一般归纳起来,就像我们说OO是什么多态,封装,继承一样,“函数式”的特征被总结为: 1。无副作用。 2。高阶函数。 3。延迟计算 而最最有意义的(至少我认为如此),是基于高阶函数的函数组合能力。一些人把这叫做glue。 简短地说,什么让函数式编程如此强大?是用简单的函数组合出复杂函数的能力。 我可以想象,说到这里,你还是一头雾水。“什么是组合?1+1不是也把两个1组合成2了吗?new A(new B(), new C())不也是从B和C组合成A了?”
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值