Master_T
Master_T

Reputation: 8007

Java: converting a "string expression" into an actual String

This might sound like an odd request, but I wanted to know if there's a straightforward way in Java of converting a "Java String declaration" into an actual String.

Let me make it clear with an example. I want to read something like this:

"This is an example " +
"of a complex\nString declaration " +
"in Java"

into a String object that will contain:

"This is an example of a complex\nString declaration in Java"

(escapes such as \n should be treaded as actual escapes, not as raw text).

EXPLANATION OF WHY: Since I guess people are gonna ask, let me explain the rationale behind this. I'm using a Java parsing library that can analyze a Java file and from which I can extract the values of, for example, an annotation or a constant. However, the parser is somewhat limited, and will not recognize complex concatenations and escaping like the one above, so basically I end up with just the whole first example as a raw string, and I have to parse and concatenate and escape it by myself. I just wondered if there's some built-in way (maybe via reflection?) to do it.

EDIT: I know that I can do some "rough" parsing quite easily (for example: split on the "+" signs and then trim, merge, erase the quotes, etc., but I don't know all the variations that there may be (how many operators do strings support? Just concatenations or there are others?? And how many escape macros are there?)

Upvotes: 0

Views: 567

Answers (1)

lance-java
lance-java

Reputation: 28099

I think you could possibly solve your problem using QDox

It parses source files into a model of JavaClass, JavaField and JavaMethod etc, each have an accessor to get the underlying source code as a String.

Upvotes: 1

Related Questions