Computing string concatenation value

Is there an *easy* way to compute a string concatenation?

String foo = "FOO";
String foobar = foo + "BAR"; // I want to compute this PsiPolyadicExpression value, that is "FOOBAR"
String foofoobarbaz = foo + foobar + "BAZ" // I want to compute this PsiPolyadicExpression, that is "FOOFOOBARBAZ"

I guess I could iterate over PsiPolyadicExpression operands, find references etc. manually. But I don't want to :)
Comment actions Permalink

Here is my  code that works well in most cases. It will work as described in initial post only if foo definition is final:

PsiPolyadicExpression parentExpression = ...;
StringBuilder computedValue = new StringBuilder();
for (PsiExpression operand : parentExpression.getOperands()) {
    if (operand instanceof PsiReference) {
        PsiElement probableDefinition = ((PsiReference) operand).resolve();
        if (probableDefinition instanceof PsiVariable) {
            PsiExpression initializer = ((PsiVariable) probableDefinition).getInitializer();
            if (initializer != null) {
                Object value = JavaConstantExpressionEvaluator.computeConstantExpression(initializer, true);
                if (value instanceof String) {
    } else {
        Object value = JavaConstantExpressionEvaluator.computeConstantExpression(operand, true);
        if (value instanceof String) {
return computedValue.toString();

Any ideas how to improve?
Alexey Kudravtsev
Comment actions Permalink

No, there is no standard component to evaluate this, since the task is too complex unfortunately.
In the more general case for example, you'll have to compute the data flow graph to be able to see the correct values for variables, e.g.

String x = "a";
x = "b";
return "c" + x;

In the simple case this code will work though.


Please sign in to leave a comment.