Replace String literals in a file with constants

Answered

Hi,
I have a scenario where a file contains string literals which I would like to replace with Constants defined in another file.
e.g.:
file X.java
Class X()
{
...
writeStringLiteral("abc");
writeStringLiteral("xyz");
...
}
_
file Constants.java_
interface Constants
{
String ABC = "abc";
String XYZ = "xyz";
}

I would like to invoke action which would replace all the string literals defined in X.java
with corresponding constants defined in Constants.java. Basically the action should take two inputs
1. the file on which it works (the file in which literals changed)
2. the file in which to search for Constant corresponding to a literal

Please let me know if any one knows of existing plugging or any way of achieving it easily

5 comments

You can't do all of them, but you can do them one-by-one with the "Introduce Constant" refactoring. If you enable the "Hardcoded Strings" inspection, it will highlight those strings, and make the refactoring available as a quickfix.

--Dave Griffith

0

Hi Dave,
Thanks for your reply. But this does not solve the problem I have mentioned.
After If I enable Hard Coded string inspection, the only fix available was to introduce a constant or make it i18N . I donot want to introduce a new constant. Constants are already defined, I want idea to use the constant defined for the literal in particular file.

Thanks
Vishwam

0

There is Settings|Errors|Duplicate String literal inspection that might help

--
regards,
--
Alexey Kudravtsev
Software Developer
JetBrains, Inc, http://www.jetbrains.com
"Develop with pleasure!"

"Vishwam" <no_mail@jetbrains.com> wrote in message
news:29201363.1158831259767.JavaMail.itn@is.intellij.net...

Hi Dave,
Thanks for your reply. But this does not solve the problem I have
mentioned.
After If I enable Hard Coded string inspection, the only fix available was
to introduce a constant or make it i18N . I donot want to introduce a new
constant. Constants are already defined, I want idea to use the constant
defined for the literal in particular file.

>

Thanks
Vishwam



0

I also feel the need to add such refactoring; if for example I've added an interface with a number of String constants, I could for example choose "Refactoring/Apply string constants from a source" and choose the source (interface of class) with a constants; and it would replace all applicable literals with corresponding names (choosing type of import would also be useful)

0

Please sign in to leave a comment.