Chris Lercher
Chris Lercher

Reputation: 37778

Conversion of Java Object to Java source code literal

I'm looking for a function that converts basic Java Objects like Strings, doubles, longs, chars, (and maybe even arrays) etc. into Java literal Strings that can be used in Java source code, e.g.

    String str = "hello";
    double d = 1.5;
    long myLong = 100L;
    int[] ints = new int[] { 5, 6 };

    System.out.println(toLiteral(str)); // prints "hello" (including double quotes!)
    System.out.println(toLiteral(d)); // prints 1.5
    System.out.println(toLiteral(myLong)); // prints 100L (including the L)
    System.out.println(toLiteral(ints)); // (bonus) prints new int[] { 5, 6 }

I would much prefer existing JavaSE or library code over a custom solution.

Upvotes: 1

Views: 117

Answers (1)

Chris Lercher
Chris Lercher

Reputation: 37778

While waiting for a library method that could do a better job, I wrote my own solution, which covers the types I need. I included some primitive arrays, as well as Instants (with local timezone for better readability). Feel free to extend this with other useful types.

import static org.apache.commons.text.StringEscapeUtils.escapeJava; // Apache commons-text
import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;

public static final ZoneId ZONE = ...;

public static String toJavaLiteralStr(final Object o) {

  if (o instanceof Long)
    return o + "L";
  else if (o instanceof Integer)
    return o.toString();
  else if (o instanceof Double)
    return o.toString();
  else if (o instanceof String s)
    return "\"" + escapeJava(s) + "\"";
  else if (o instanceof Character c)
    return "'" + (c == '\'' ? "\\'" : c) + "'";
  else if (o instanceof int[] ints)
    return "new int[] {" + convertArray(Arrays.stream(ints).boxed()) + "}";
  else if (o instanceof long[] longs)
    return "new long[] {" + convertArray(Arrays.stream(longs).boxed()) + "}";
  else if (o instanceof double[] doubles)
    return "new double[] {" + convertArray(Arrays.stream(doubles).boxed()) + "}";
  else if (o instanceof Instant instant)
    return "Instant.parse(\"" + instant.atZone(ZONE).format(ISO_OFFSET_DATE_TIME) + "\")";
  else
    throw new IllegalArgumentException("Unknown argument type: " + o.getClass().getName());
}

private static String convertArray(final Stream<?> boxedStream) {
  return boxedStream.map(o -> toJavaLiteralStr(o)).collect(Collectors.joining(", "));
}

Upvotes: 1

Related Questions