From cf99dafa5bb2c62f67e72929747e93294824cac8 Mon Sep 17 00:00:00 2001 From: Yufeng Wang Date: Fri, 1 Sep 2023 07:29:09 -0700 Subject: [PATCH] Fix failing to find Optional class issue (#28991) --- src/lib/support/JniReferences.cpp | 35 +++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/lib/support/JniReferences.cpp b/src/lib/support/JniReferences.cpp index de61a98d74641d..870ec3fc2d1d56 100644 --- a/src/lib/support/JniReferences.cpp +++ b/src/lib/support/JniReferences.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ +#include #include #include #include @@ -79,8 +80,17 @@ CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass CHIP_ERROR err = CHIP_NO_ERROR; jclass cls = nullptr; - cls = env->FindClass(clsType); - env->ExceptionClear(); + // Try `j$/util/Optional` when enabling Java8. + if (strcmp(clsType, "java/util/Optional") == 0) + { + cls = env->FindClass("j$/util/Optional"); + } + + if (cls == nullptr) + { + env->ExceptionClear(); + cls = env->FindClass(clsType); + } if (cls == nullptr) { @@ -121,6 +131,20 @@ CHIP_ERROR JniReferences::FindMethod(JNIEnv * env, jobject object, const char * VerifyOrReturnError(javaClass != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND); *methodId = env->GetMethodID(javaClass, methodName, methodSignature); + + // Try `j$` when enabling Java8. + std::string methodSignature_java8_str(methodSignature); + if (*methodId == nullptr && methodSignature_java8_str.find("java/util/Optional") != std::string::npos) + { + // Replace all "java/util/Optional" with "j$/util/Optional". + while (methodSignature_java8_str.find("java/util/Optional") != std::string::npos) + { + size_t pos = methodSignature_java8_str.find("java/util/Optional"); + methodSignature_java8_str.replace(pos, strlen("java/util/Optional"), "j$/util/Optional"); + } + *methodId = env->GetMethodID(javaClass, methodName, methodSignature_java8_str.c_str()); + } + VerifyOrReturnError(*methodId != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); return err; @@ -193,6 +217,13 @@ CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOpti chip::JniClass jniClass(optionalCls); jmethodID ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Ljava/util/Optional;"); + + // Try `Lj$/util/Optional;` when enabling Java8. + if (ofMethod == nullptr) + { + ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Lj$/util/Optional;"); + } + VerifyOrReturnError(ofMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND); outOptional = env->CallStaticObjectMethod(optionalCls, ofMethod, objectToWrap);