WEB开发网
开发学院软件开发Java Java 编程的动态性,第 6 部分: 利用 Javassist 进... 阅读

Java 编程的动态性,第 6 部分: 利用 Javassist 进行面向方面的更改

 2010-03-18 00:00:00 来源:WEB开发网   
核心提示: 清单 3. 一个类剖析程序publicclassDissect{publicstaticvoidmain(String[]args){if(args.length>=1){try{//setupclassloaderwithtranslatorTranslatorxlat=newDisse

清单 3. 一个类剖析程序

public class Dissect 
{ 
  public static void main(String[] args) { 
    if (args.length >= 1) { 
      try { 
         
        // set up class loader with translator 
        Translator xlat = new DissectionTranslator(); 
        ClassPool pool = ClassPool.getDefault(xlat); 
        Loader loader = new Loader(pool); 
           
        // invoke the "main" method of the application class 
        String[] pargs = new String[args.length-1]; 
        System.arraycopy(args, 1, pargs, 0, pargs.length); 
        loader.run(args[0], pargs); 
         
      } catch (Throwable ex) { 
        ex.printStackTrace(); 
      } 
       
    } else { 
      System.out.println 
        ("Usage: Dissect main-class args..."); 
    } 
  } 
   
  public static class DissectionTranslator implements Translator 
  { 
    public void start(ClassPool pool) {} 
     
    public void onWrite(ClassPool pool, String cname) 
      throws NotFoundException, CannotCompileException { 
      System.out.println("Dissecting class " + cname); 
      CtClass clas = pool.get(cname); 
      clas.instrument(new VerboseEditor()); 
    } 
  } 
   
  public static class VerboseEditor extends ExprEditor 
  { 
    private String from(Expr expr) { 
      CtBehavior source = expr.where(); 
      return " in " + source.getName() + "(" + expr.getFileName() + ":" + 
        expr.getLineNumber() + ")"; 
    } 
    public void edit(FieldAccess arg) { 
      String dir = arg.isReader() ? "read" : "write"; 
      System.out.println(" " + dir + " of " + arg.getClassName() + 
        "." + arg.getFieldName() + from(arg)); 
    } 
    public void edit(MethodCall arg) { 
      System.out.println(" call to " + arg.getClassName() + "." + 
        arg.getMethodName() + from(arg)); 
    } 
    public void edit(NewExpr arg) { 
      System.out.println(" new " + arg.getClassName() + from(arg)); 
    } 
  } 
} 

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:Java 编程 动态性

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接