From 1aa3c1e543197ce34ceafeb407ea268d044f029a Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Thu, 18 Aug 2022 16:41:28 +0200 Subject: [PATCH] java/String: add static method Optional() --- src/java/String.hxx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/java/String.hxx b/src/java/String.hxx index f60e7abc7..716268f02 100644 --- a/src/java/String.hxx +++ b/src/java/String.hxx @@ -89,6 +89,16 @@ public: String(JNIEnv *_env, const char *_value) noexcept :LocalRef(_env, _env->NewStringUTF(_value)) {} + /** + * This constructor allows passing a nullptr value, which maps + * to a "null" in Java. + */ + static String Optional(JNIEnv *_env, const char *_value) noexcept { + return _value != nullptr + ? String{_env, _value} + : String{}; + } + static StringUTFChars GetUTFChars(JNIEnv *env, jstring s) noexcept { return {env, s, env->GetStringUTFChars(s, nullptr)}; }