Count Total Number of Methods in a Java Project

This code example is for counting total number of methods in projects under Eclipse work space. We can use Eclipse JDT – Java Model to do this. Counting total number of method in a certain java project is a very simple task.

The following code works under Eclipse Plug-in project only. If you don’t know how to create a Plug-in, you can read How to create a plug-in.

private void processRootDirectory() throws JavaModelException,
		CoreException {
	IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
	System.out.println("root" + root.getLocation().toOSString());
 
	IProject[] projects = root.getProjects();
 
	// process each project
	for (IProject project : projects) {
 
		System.out.println("project name: " + project.getName());
 
		if (project.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
			IJavaProject javaProject = JavaCore.create(project);
			IPackageFragment[] packages = javaProject.getPackageFragments();
 
			// process each package
			for (IPackageFragment aPackage : packages) {
 
				// We will only look at the package from the source folder
				// K_BINARY would include also included JARS, e.g. rt.jar
				// only process the JAR files
				if (aPackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
 
					for (ICompilationUnit unit : aPackage
							.getCompilationUnits()) {
 
						System.out.println("--class name: "
								+ unit.getElementName());
 
						IType[] allTypes = unit.getAllTypes();
						for (IType type : allTypes) {
 
							IMethod[] methods = type.getMethods();
 
							for (IMethod method : methods) {
								totalMethod++;
								System.out.println("--Method name: "+ method.getElementName());
								System.out.println("Signature: "+ method.getSignature());
								System.out.println("Return Type: "+ method.getReturnType());
								System.out.println("source: "+ method.getSource());
								System.out.println("to string: "+ method.toString());
								System.out.println("new: "+ method.getPath().toString());
							}
						}
					}
				}
			}
 
		}
 
	}
}

Reference:
1. create a simple eclipse plug-in application

Leave a Comment