4 Ağustos 2023 Cuma

JEP 430 - java.lang.StringTemplate.Processor Arayüzü - JDK 21 İle Geliyor Custom Template Processor İçindir

Giriş
Açıklaması şöyle
Template processing is built upon the newly added nested functional interface java.lang.StringTemplate.Processor:
How the processing works is that the String literal containing the expression is converted to a StringTemplate and given to a Processor.

If we want to create a JSONObject, we need to interpolate the String literal first, and then create the new instance of the desired return type. Using the static helper Processor.of makes this quite easy:
@FunctionalInterface
public interface Processor<R, E extends Throwable> {

  R process(StringTemplate stringTemplate) throws E;

  static <T> Processor<T, RuntimeException> of(
    Function<? super StringTemplate, ? extends T> process) {
    return process::apply;
  }

  // ...
}
of metodu
Örnek
Açıklaması şöyle
How the processing works is that the String literal containing the expression is converted to a StringTemplate and given to a Processor.

If we want to create a JSONObject, we need to interpolate the String literal first, and then create the new instance of the desired return type. Using the static helper Processor.of makes this quite easy:
Şöyle yaparız Önce bir Processor yaratıyoruz. Sonra StringTemplate nesnesi Processor'a geçiliyor.
/// CREATE NEW TEMPLATE PROCESSOR
var JSON = StringTemplate.Processor.of(
  (StringTemplate template) -> new JSONObject(template.interpolate())
);

// USE IT LIKE BEFORE
JSONObject json = JSON."""
{
  "user": "\{
    // We only want to use the firstname
    this.user.firstname()
  }",
  "temperatureCelsius: \{tempC}
}
""";
StringTemplate.Processor<JSONObject, JSONException> JSON = template -> {
  String quote = "\"";
  List<Object> newValues = new ArrayList<>();

  for (Object value : template.values()) {
    if (value instanceof String str) {
      // SANITIZE STRINGS
      // the many backslashes look weird, but it's the correct regex
      str = str.replaceAll(quote, "\\\\\"");
      newValues.add(quote + str + quote);
    }
    else if (value instanceof Number || value instanceof Boolean) {
      newValues.add(value);
    }
    // TODO: support more types
    else {
      throw new JSONException("Invalid value type");
    }
  }

  var json = StringTemplate.interpolate(template.fragments(), newValues);

  return new JSONObject(json);
};




Hiç yorum yok:

Yorum Gönder