text analysis - Retrieve code executed by function in Java -
i'm trying analyse bits of java-code, looking if code written complexly. start string containing contents of java-class. there want retrieve, given function-name, "inner code" function. in example:
public class testclass{ public int testfunction(char x) throws exception{ if(x=='a'){ return 1; }else if(x=='{'){ return 2; }else{ return 3; } } public int testfunctiontwo(int y){ return y; } }
i want get, when call string code = getcode("testfunction");
, code
contains if(x=='a'){ ... return 3; }
. i've made input code ugly, demonstrate of problems 1 might encounter when doing character-by-character-analysis (because of else if
, curly brackets no longer match, because of exception thrown, function declaration not of form functionname{ //contents }, etc.)
is there solid way contents of testfunction
, or should implement problems described manually?
you need java parser. worked qdox. easy use. example here:
import com.thoughtworks.qdox.javaprojectbuilder; import com.thoughtworks.qdox.model.javaclass; import com.thoughtworks.qdox.model.javamethod; import java.io.file; import java.io.ioexception; public class parser { public void parsefile() throws ioexception { file file = new file("/path/to/testclass.java"); javaprojectbuilder builder = new javaprojectbuilder(); builder.addsource(file); (javaclass javaclass : builder.getclasses()) { if (javaclass.getname().equals("testclass")) { (javamethod javamethod : javaclass.getmethods()) { if (javamethod.getname().equals("testmethod")) { system.out.println(javamethod.getsourcecode()); } } } } } }
Comments
Post a Comment