Switching to a Java package implementation in Emacs

There already quite a few methods to switch between header and implementation of C and C++ sources in Emacs. Maybe I will put one of those here as well later. But now I needed something different: In a big project, I would like to point at a line like import com.foo.tech.implementation.SomeClass; and Emacs automatically visits the file where this class has been implemented. I wrote two small Elisp functions to perform this:

(defun my-switch-to-java-implementation (packagename classname)
"Tries to switch to the java source file containing the package packagename and
the class classname."
(format "%s %s -iname '*.java' | xargs egrep -l '%s' | sort -u | xargs egrep -l 'class %s' | head -n 1"
(current-buffer) )
(if (= (count-lines (point-min) (point-max) ) 1)
(search-forward "n")
(replace-match "")
(find-file (buffer-string))
(message "Could not find suitable implementation.")

(defun my-switch-to-java-implementation-at-point ()
"Tries to switch to the java source file which contains the package and class imported
in the current line."
(if (looking-at "^import \(.*\)\.\(.+\);$")
(let ( (packagename (buffer-substring (match-beginning 1) (match-end 1) ) )
(classname (buffer-substring (match-beginning 2) (match-end 2) ) ) )
(my-switch-to-java-implementation packagename classname)
(message "This is not an import")

You basically call my-switch-to-java-implementation-at-point (e.g. by binding it to a key) when you are on the import line. Emacs then launches find and grep to look for the definition of your class. Of course, using something like GNU Global would be faster, but also a bit more tricky, since it does not use the packagename, but rather only the class name, which might be used multiple times in your project.
Also note that you have to set the path to your Java source files. I suggest you make a customizable variable of that, or use your ede-project-root or something similar.

Leave a Reply

Your email address will not be published.