- Java: Parse Java Source Code, Extract Methods
- Prerequisites
- Steps
- Explanation
- Conclusion
- How To Parse Java Source Code Use JDK Parser
- 1. Parse Java Source Code Use JDK Parser Steps.
- 2. JavaSourceVisitor.java
- 3. JavaMethodDTO.java
- 4. JavaFileParser.java
- Java Parse String
- Initialization of Parse String
- Example #1
- Example #2
- Example #3
- Example #4
- Example #5
- Conclusion – Java Parse String
- Recommended Articles
Java: Parse Java Source Code, Extract Methods
Parsing Java source code is a useful technique that can be used to extract various information such as methods, class declarations, and variable declarations, among others. In this guide, we will focus on how to parse Java source code and extract methods using code examples.
Prerequisites
Before we get started, you will need to have the following:
- Java Development Kit (JDK) installed
- An Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA
Steps
- Create a new Java project in your IDE.
- Add the following Maven dependency to your project’s pom.xml file:
org.eclipse.jdt org.eclipse.jdt.core 3.24.0
This dependency is required for parsing Java source code using the Eclipse Java Development Tools (JDT) library.
- Create a new Java class and add the following code to parse a Java source file and extract its methods:
import java.io.File; import java.util.ArrayList; import java.util.List; import org.eclipse.jdt.core.dom.*; public class JavaParser < public static void main(String[] args) < String filePath = "path/to/java/source/file.java"; Listmethods = new ArrayList<>(); ASTParser parser = ASTParser.newParser(AST.JLS11); parser.setKind(ASTParser.K_COMPILATION_UNIT); parser.setSource(FileUtils.readFileToString(new File(filePath)).toCharArray()); CompilationUnit cu = (CompilationUnit) parser.createAST(null); cu.accept(new ASTVisitor() < public boolean visit(MethodDeclaration node) < methods.add(node.getName().toString()); return true; >>); System.out.println("Methods: " + methods); > >
- Replace “path/to/java/source/file.java” with the path to your Java source file.
- Run the JavaParser class and you should see a list of methods in your Java source file printed to the console.
Explanation
Let’s go through the code step by step.
- We first define the path to our Java source file and create an empty list to store the names of the methods we will extract.
- We then create a new ASTParser object and set its source to the contents of our Java source file using the FileUtils class.
- We also set the parser’s kind to K_COMPILATION_UNIT, which tells it that we want to parse a single compilation unit (i.e., a single Java source file).
- We then create a CompilationUnit object from the parser’s AST and traverse it using an ASTVisitor object.
- Inside the visitor’s visit() method, we check if the node being visited is a MethodDeclaration (i.e., a method in our Java source file).
- If it is, we extract the name of the method and add it to our list of methods.
- Finally, we print out the list of methods to the console.
Conclusion
In this guide, we have shown you how to parse Java source code and extract methods using the Eclipse JDT library. This technique can be useful for a variety of tasks such as code analysis, code generation, and refactoring. With some modifications, you can also extract other information such as class declarations, variable declarations, and annotations. Happy coding!
How To Parse Java Source Code Use JDK Parser
This article will show you how to parse out one java class’s methods via the JDK parser. It will parse out the method modifier, return type, name, parameters, threw exceptions, and method body.
1. Parse Java Source Code Use JDK Parser Steps.
- To do this task, you should first extend the class com.sun.source.util.TreeScanner to create a subclass that can visit the java source code, and override the subclass’s method as you need. All the method will be invoked when the parser read the target java class source code.
- Because we emphasize the parse method, so we just need to override the methodvisitMethod(MethodTree mt, Object obj).
- You can also override the method visitVariable(VariableTree arg0, Object arg1) if you want to parse class variables.
2. JavaSourceVisitor.java
- Below java class is the subclass of the class com.sun.source.util.TreeScanner, it override the method visitMethod(MethodTree mt, Object obj).
package com.general.common.parser; import java.util.ArrayList; import java.util.List; import com.general.common.dto.JavaMethodDTO; import com.general.common.util.StringTool; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; public class JavaSourceVisitor extends TreeScanner < private List methodList = new ArrayList(); public List getMethodList() < if(methodList==null) < methodList = new ArrayList(); >return methodList; > public void setMethodList(List methodList) < this.methodList = methodList; >@Override public Object visitMethod(MethodTree mt, Object obj) < if(mt!=null) < JavaMethodDTO javaMethodDto = new JavaMethodDTO(); String modifier = StringTool.getObjectStringValue(mt.getModifiers()); System.out.println("mt.getModifiers() : " + modifier); String returnType = StringTool.getObjectStringValue(mt.getReturnType()); System.out.println("mt.getReturnType() : " + returnType); String methodName = StringTool.getObjectStringValue(mt.getName()); System.out.println("mt.getName() : " + methodName); List paramStrList = new ArrayList(); ListparamList = mt.getParameters(); if(paramList!=null) < for(VariableTree vt : paramList) < String paramStr = StringTool.getObjectStringValue(vt); System.out.println("param : " + paramStr); paramStrList.add(paramStr); >> //System.out.println("mt.getDefaultValue() : " + StringTool.getObjectStringValue(mt.getDefaultValue())); //System.out.println("mt.getKind() : " + StringTool.getObjectStringValue(mt.getKind())); List throwsStrList = new ArrayList(); List throwsList = mt.getThrows(); if(throwsList!=null) < for(ExpressionTree et : throwsList) < String throwsStr = StringTool.getObjectStringValue(et); System.out.println("throws : " + throwsStr); throwsStrList.add(throwsStr); >> String methodBody = StringTool.getObjectStringValue(mt.getBody()); System.out.println("mt.getBody() : " + methodBody); javaMethodDto.setMethodModifier(modifier); javaMethodDto.setMethodReturnType(returnType); javaMethodDto.setMethodName(methodName); javaMethodDto.setMethodParamList(paramStrList); javaMethodDto.setMethodThrowsList(throwsStrList); javaMethodDto.setMethodBody(methodBody); this.methodList.add(javaMethodDto); > if(obj!=null) < System.out.println(obj.toString()); >return super.visitMethod(mt, obj); > @Override public Object visitVariable(VariableTree arg0, Object arg1) < return super.visitVariable(arg0, arg1); >>
3. JavaMethodDTO.java
package com.general.common.dto; import java.util.ArrayList; import java.util.List; public class JavaMethodDTO extends BaseDTO < private String methodModifier = ""; private String methodReturnType = ""; private String methodName = ""; private List methodParamList = new ArrayList(); private List methodThrowsList = new ArrayList(); private String methodBody = ""; public String getMethodModifier() < return methodModifier; >public void setMethodModifier(String methodModifier) < this.methodModifier = methodModifier; >public String getMethodReturnType() < return methodReturnType; >public void setMethodReturnType(String methodReturnType) < this.methodReturnType = methodReturnType; >public String getMethodName() < return methodName; >public void setMethodName(String methodName) < this.methodName = methodName; >public List getMethodParamList() < if(methodParamList==null) < methodParamList = new ArrayList(); >return methodParamList; > public void setMethodParamList(List methodParamList) < this.methodParamList = methodParamList; >public String getMethodBody() < return methodBody; >public void setMethodBody(String methodBody) < this.methodBody = methodBody; >public List getMethodThrowsList() < if(methodThrowsList==null) < methodThrowsList = new ArrayList(); >return methodThrowsList; > public void setMethodThrowsList(List methodThrowsList) < this.methodThrowsList = methodThrowsList; >>
4. JavaFileParser.java
- This java class JavaFileParser is the place where we invoke the instance of the java class JavaSourceVisitor and get the parsed-out result.
- JavaFileParser.java
package com.general.common.parser; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import com.general.common.dto.JavaMethodDTO; import com.general.common.util.StringTool; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.util.JavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.file.JavacFileManager; import com.sun.tools.javac.util.Context; public class JavaFileParser < private JavacFileManager jcFileManager; private JavacTool jcTool; public JavaFileParser() < Context context = new Context(); jcFileManager = new JavacFileManager(context, true, Charset.defaultCharset()); jcTool = new JavacTool(); >public static void main(String[] args) < String javaFilePath = "D:/Workspace/test.java"; JavaFileParser jfp = new JavaFileParser(); jfp.parseJavaSourceFile(javaFilePath); >public List parseJavaSourceFile(String filePath) < List retMethodList = new ArrayList(); if(!StringTool.isEmpty(filePath)) < /* Create a Java Source Visitor object. */ JavaSourceVisitor jsv = new JavaSourceVisitor(); /* Get files object list from the java file path.*/ IterablejavaFiles = jcFileManager.getJavaFileObjects(filePath); /* Get the java compiler task object. */ JavaCompiler.CompilationTask cTask = jcTool.getTask(null, jcFileManager, null, null, null, javaFiles); JavacTask jcTask = (JavacTask) cTask; try < /* Iterate the java compiler parse out task. */ IterablecodeResult = jcTask.parse(); for (CompilationUnitTree codeTree : codeResult) < /* Parse out one java file source code.*/ codeTree.accept(jsv, null); >/* Get the parsed out method list. */ retMethodList = jsv.getMethodList(); >catch (IOException e) < e.printStackTrace(); >> return retMethodList; > public void parseJavaSourceString(String javaSourceCode) < if(!StringTool.isEmpty(javaSourceCode)) < >> >
mt.getModifiers() : public mt.getReturnType() : mt.getName() : param : PNConfiguration initialConfig mt.getBody() : < this.configuration = initialConfig; this.mapper = new MapperManager(); this.basePathManager = new BasePathManager(initialConfig); this.retrofitManager = new RetrofitManager(this); this.subscriptionManager = new SubscriptionManager(this, retrofitManager); this.pub1ishSequenceManager = new Pub1ishSequenceManager(MAX_SEQUENCE); instanceId = UUID.randomUUID().toString(); >mt.getModifiers() : public mt.getReturnType() : String mt.getName() : getBaseUr1 mt.getBody() :
Java Parse String
Parsing String in java is known as converting data in the String format from a file, user input, or a certain network. Parsing String is the process of getting information that is needed in the String format. String parsing in java can be done by using a wrapper class. Using the Split method, a String can be converted to an array by passing the delimiter to the split method. The split method is one of the methods of the wrapper class.
Web development, programming languages, Software testing & others
String parsing can also be done through StringTokenizer. StringTokenizer class allows its constructor to break the String into tokens. StringTokenizer is much simpler than other classes. StringTokenizer is a legacy class, so everyone must avoid the use of this class.
String strMsg = "An Example of String"; String delims = "[delimiters]+"; String tokenString = strMsg.split(delims);
In the above syntax, multiple delimiter can be used inside the square brackets. “+” sign after bracket treats multiple delimiter as a single delimiter.
Initialization of Parse String
In java, a String can be converted into char, Object, int, date, time, etc. String parsing is initialized by a certain java class method as per the data type is required.
Example #1
In this example, we can see how String is parsing into different types of formats like date & integer. Similarly, we can use other methods to convert a string into other formats.
import java.text.SimpleDateFormat; import java.util.Date; public class StringParsingInDiffTypeExample < public static void main(String[] args)throws Exception < System.out.println("String parsing into Date Oject : \n"); String strDate1 = "12/01/2020"; String strDate2 = "12-Jan-2020"; String strDate3 = "Sun, Jan 12 2020"; //converting date format into the date object here SimpleDateFormat strFormat1 = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat strFormat2 = new SimpleDateFormat("dd-MMM-yyyy"); SimpleDateFormat strFormat3 = new SimpleDateFormat("E, MMM dd yyyy"); //date retrieving here after parsing through parse method Date dateObj1 = strFormat1.parse(strDate1); Date dateObj2 = strFormat2.parse(strDate2); Date dateObj3 = strFormat3.parse(strDate3); //printing here the date as a char System.out.println("Date String 1 = " + strDate1 + "\t Date Object 1 = " + dateObj1); System.out.println("Date String 2 = " + strDate2 + "\t Date Object 2 = " + dateObj2); System.out.println("Date String 3 = " + strDate3 + "\t Date String 3 = " + dateObj3); System.out.println("\n\nString parsing into integer : \n"); String strVal1 = "50"; String strVal2 = "1000"; String strVal3 = "20000"; //Converting String into int using parseInt() int intValue1 = Integer.parseInt(strVal1); int intValue2 = Integer.parseInt(strVal2); int intValue3 = Integer.parseInt(strVal3); //Printing integer value System.out.println(intValue1); System.out.println(intValue2); System.out.println(intValue3); >>
Output for the above-given program is given below; we can see how String is converted into different data type by using different methods.
Example #2
In this example, using the split method for parsing of the string to array format.
public class SplitMethodExample < public static void main(String args[])< System.out.println("String Parsing Example #1 :\n"); //In this example one space character is used as a delimiter String str1 = new String("Nothing is impossible in the world!"); String delimSpace = " "; String[] arr1 = str1.split(delimSpace); for (String uniqVal1 : arr1) < System.out.println(uniqVal1); >System.out.println("\n\nString Parsing Example #2 :\n"); //In this example a comma is used as a delimiter String str2 = new String("Alabama,California,texas,30,78"); String delimsComma = "[,]+"; String[] arr2 = str2.split(delimsComma); for (String uniqVal2 : arr2) < System.out.println(uniqVal2); >System.out.println("\n\nString Parsing Example #3 :\n"); //In this example multiple delimiter is used used as a delimiter String str3 = new String("Many of the people always say without thinking ,do you know ?Possibly Not!"); String delims = "[. ]+"; String[] arr3 = str3.split(delims); for (String uniqVal3 : arr3) < System.out.println(uniqVal3); >> >
The above given an example contains three sections, all the three-section using the different delimiter for parsing the String. In the below-given screenshot, we can see the output of the above-given program.
Example #3
In this example, the StringTokenizer class is used for parsing. The StringTokenizer class’s constructor takes two parameters: the first one is the string & the second one is the delimiter. This class contains some methods, i.e. hasMoreElements() to check whether the next index holding any value or not while nextElement() returns the value at the next index.
import java.util.StringTokenizer; public class StringTokenizerParsingExample < public static void main(String[] args) < System.out.println("StringTokenizer Parsing Example: \n"); String strText = "Kansas,Louisiana,Maryland,Massachusetts,Mississippi,New Jersey"; String delims = ","; StringTokenizer stObj = new StringTokenizer(strText, delims); //Iterating here for the next element while (stObj.hasMoreElements()) < System.out.println("StringTokenizer Output: " + stObj.nextElement()); >> >
Output:
The above parsing output is given below; we can see how comma-separated values are listed in the next column.
Example #4
This example shows how the indexOf method can be used effectively to parse any String in java. In this program, a String in the middle of the sentence is being converted to uppercase.
public class StringParsingExample < public static void main(String args[])< String strPara = "The Paragraph needs additional citations for [verification]"; int openIndex = strPara.indexOf("["); int closedIndex = strPara.indexOf("]"); // extracting here the String inside of the square bracket String subString = strPara.substring(openIndex+1, closedIndex); //converting substring in the uppercase which is inside of subString= subString.toUpperCase(); // concating here all the substrings String modifiedPara = strPara.substring(0, openIndex + 1) + subString + strPara.substring(closedIndex); System.out.println(modifiedPara); >>
Output: Output of the above-given program is given below.
Example #5
In this example, we can see how a string is converted into an array of chars.
public class StringParsingCharExample < public static void main(String[] args) < String strText = "Australia"; char[] charArr = strText.toCharArray(); System.out.println(charArr.length); char secondPosChar = strText.charAt(2); System.out.println(secondPosChar); char[] charSet = new char[9]; strText.getChars(0, 9, charSet, 0); for (char uniqChar : charSet) < System.out.println(uniqChar); >> >
Output:
The Output for the above-given program is given below.
In the attached output screenshot, we can see how a String is converted into the array of characters by using methods toCharArray().
Conclusion – Java Parse String
In the above-given Article, we have gone through the parsing, String parsing in Java, etc. How the split method plays a role in parsing the data type. Some other ways are also available which can be used for parsing, such as StringTokenizer.
Recommended Articles
This has been a guide to Java Parse String. Here we discuss the syntax and initialization of the Java Parse String. you may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8