Home » Java » java – automatically replace string literals in source code with existing constants from included classes (In eclipse)-Exceptionshub

java – automatically replace string literals in source code with existing constants from included classes (In eclipse)-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m mainly working with Magnolia CMS / JCR where I have to use a lot of string constants to set the type of jcr nodes or specific properties in the content repository. For example JcrConstants defines many constants:

package org.apache.jackrabbit;
...
public interface JcrConstants {
...
public static final String NT_FOLDER = "nt:folder";
...
}

When I write my code, I (and colleagues) often use hard coded string literals. It’s easy to memorize the often used strings like “nt:folder”, but not so easy in which package I can find a corresponding constant like JcrConstants.NT_FOLDER. I’m talking about 30-40 strings in maybe 5-10 packages.

Is there a way (in eclipse) to automatically replace "nt:folder" in my class with JcrConstants.NT_FOLDER or autosuggest (similar to the Add import method in eclipse Shift+Crtl+O) a constant existing in any of the included (maven) packages?

In eclipse you can extract constants via Refactor > Extract Constant… (Alt+T, A), but this simply creates a constant in the current class.
Then you end up with a new constant in each class. What I want a to use an already defined constant in all classes.

The closest I could find is instasearch which is not supported anymore and does not work in eclipse 4.x. Instasearch was capable of searching in the source of maven packages. Then you could search for string literals in the source code to find existing constants, still quite some manual work though.

How to&Answers: