How to format Java Code by using Eclipse JDT?

If you use eclipse, you probably format your code by pressing Ctrl+Shift+F or right clicking Source -> Format very often. This function is also provide in JDT, so you can also format your Java code in Java code.

Finding the correct JDT API for doing this job, however, is not straight-forward. In the following code, you will see one of the classes being used is actually an internal class.

Read more

Get Internal Comments By Using Eclipse JDT ASTParser

You may try to use Eclipse JDT ASTParser to parse Java source files, but cannot get the list of internal comments in the .java file. There is a method called getCommentList from the CompilationUnit class. But if you use it, you find that it returns a list of empty comments. How to get internal comments … Read more

ASTParser ignore embedded inner class

When using Eclipse ASTParser, if you want to get all methods and fields of the outer class and ignore the embedded inner class(es), you may try to visit all methods and fields and try to differentiate outer class and inter class.

Each class is a TypeDeclaration in AST, and Inner class is another TypeDeclaration inside the TypeDeclaration in the AST. The key question is: how to know if stuff is in a root TypeDeclaration or a inner TypeDeclaration?

Read more

Insert/Add Statements to Java Source Code by using Eclipse JDT ASTRewrite

This belongs to Eclipse JDT Tutorial Series. This code example is for inserting a statement to existing Java source code by using eclipse JDT. It works inside of a Plug-in. For simplicity purpose, the following code simple add a method invocation statement called “add” to the first line of a method. public class Main { … Read more

Eclipse JDT Tutorial: Find All References of a Method

When using JDT, you may want to find all references of a given method and then do something with the references. This can be done by using method JDTSearchProvider.searchMethodReference(). The following is sample code: // First of all, get all the type declaration of the class. IType [] typeDeclarationList = unit.getTypes();   for (IType typeDeclaration … Read more

Eclipse JDT Tutorial – Dynamic load Java projects to workspace

In previous post, I have shown how to use Java Model to create a new project, access an existing project, and dynamically import/load an existing project directory into workspace. The real question is if we want to parse a large number of projects(e.g. 1000) and those projects do not have .project file under it’s directory. … Read more