0

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?)

Master_T
  • 7,232
  • 11
  • 72
  • 144
  • 1
    Take a look at http://stackoverflow.com/questions/3537706/howto-unescape-a-java-string-literal-in-java – Codebender Jul 07 '15 at 08:07
  • @Codebender: the solutions there don't seem to parse concatenation, just escape commands. But it's a start, thanks – Master_T Jul 07 '15 at 08:13

1 Answers1

1

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.

lance-java
  • 25,497
  • 4
  • 59
  • 101
  • First of all, thanks for making me aware of the existence of this java parser, seems more advanced than the one I'm using. This having been said, it has the same problem: yes, I can access the "raw string" with it, but from the quick look I gave to it it doesn't seem to convert it to the actual concatenated and escaped string, unless you manually parse all the binary expressions (but If I have to do that I might as well write a parser for the raw string, it's faster) – Master_T Jul 07 '15 at 08:30