Skip to content

Commit

Permalink
Fix failing to find Optional class issue (#28991)
Browse files Browse the repository at this point in the history
  • Loading branch information
yufengwangca authored and pull[bot] committed Jan 18, 2024
1 parent a0c4e72 commit cf99daf
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/lib/support/JniReferences.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

#include <cstring>
#include <jni.h>
#include <lib/support/CHIPJNIError.h>
#include <lib/support/CodeUtils.h>
Expand Down Expand Up @@ -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)
{
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);

Expand Down

0 comments on commit cf99daf

Please sign in to comment.