1 /*** 2 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html 3 */ 4 package test.net.sourceforge.pmd.ast; 5 6 import junit.framework.TestCase; 7 import net.sourceforge.pmd.TargetJDK1_4; 8 import net.sourceforge.pmd.ast.ASTCompilationUnit; 9 import net.sourceforge.pmd.ast.JavaParser; 10 import net.sourceforge.pmd.ast.JavaParserVisitor; 11 12 import java.io.StringReader; 13 import java.lang.reflect.InvocationHandler; 14 import java.lang.reflect.Method; 15 import java.lang.reflect.Proxy; 16 import java.util.HashSet; 17 import java.util.Set; 18 19 public class ParserTst extends TestCase { 20 21 private class Collector implements InvocationHandler { 22 private Class clazz = null; 23 private Set collection = new HashSet(); 24 25 public Collector(Class clazz) { 26 this.clazz = clazz; 27 } 28 29 public Set getCollection() { 30 return collection; 31 } 32 33 public Object invoke(Object proxy, Method method, Object params[]) throws Throwable { 34 if (method.getName().equals("visit")) { 35 if (clazz.isInstance(params[0])) { 36 collection.add(params[0]); 37 } 38 } 39 40 Method childrenAccept = params[0].getClass().getMethod("childrenAccept", new Class[]{JavaParserVisitor.class, Object.class}); 41 childrenAccept.invoke(params[0], new Object[]{proxy, null}); 42 return null; 43 } 44 } 45 46 public Set getNodes(Class clazz, String javaCode) throws Throwable { 47 Collector coll = new Collector(clazz); 48 JavaParser parser = (new TargetJDK1_4()).createParser(new StringReader(javaCode)); 49 ASTCompilationUnit cu = parser.CompilationUnit(); 50 JavaParserVisitor jpv = (JavaParserVisitor) Proxy.newProxyInstance(JavaParserVisitor.class.getClassLoader(), new Class[]{JavaParserVisitor.class}, coll); 51 jpv.visit(cu, null); 52 return coll.getCollection(); 53 } 54 }