I wish to parse java source code files, and extract the methods source code.
I would need a method like this :
/** Returns a map with key = method name ; value = method source code */ Map<String,String> getMethods(File javaFile);
Is there a simple way to achieve this, a library to help me build my method, etc. ?
Method Class | getName() Method in Java Method class is helpful to get the name of methods, as a String. To get name of all methods of a class, get all the methods of that class object. Then call getName() on those method objects. Return Value: It returns the name of the method, as String.
The Period instance can be obtained from a string value using the parse() method in the Period class in Java. This method requires a single parameter i.e. the string which is to be parsed. This string cannot be null. Also, it returns the Period instance obtained from the string value that was passed as a parameter.
The JavaParser library provides you with an Abstract Syntax Tree of your Java code. The AST structure then allows you to work with your Java code in an easy programmatic way. Add Dependency Parse Analyse Transform Generate. // Create source code on the fly. CompilationUnit compilationUnit = new CompilationUnit();
Usually the parse() method receives some string as input, "extracts" the necessary information from it and converts it into an object of the calling class. For example, it received a string and returned the date that was "hiding" in this string.
Download the java parser from https://javaparser.org/
You'll have to write some code. This code will invoke the parser... it will return you a CompilationUnit:
InputStream in = null; CompilationUnit cu = null; try { in = new SEDInputStream(filename); cu = JavaParser.parse(in); } catch(ParseException x) { // handle parse exceptions here. } finally { in.close(); } return cu;
Note: SEDInputStream is a subclass of input stream. You can use a FileInputStream if you want.
You'll have to create a visitor. Your visitor will be easy because you're only interested in methods:
public class MethodVisitor extends VoidVisitorAdapter { public void visit(MethodDeclaration n, Object arg) { // extract method information here. // put in to hashmap } }
To invoke the visitor, do this:
MethodVisitor visitor = new MethodVisitor(); visitor.visit(cu, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With