Skip to content

Commit 5401076

Browse files
yufengwangcapull[bot]
authored andcommitted
Fix failing to find Optional class issue (#28991)
1 parent c1fd5aa commit 5401076

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

src/lib/support/JniReferences.cpp

+33-2
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
* limitations under the License.
1616
*/
1717

18+
#include <cstring>
1819
#include <jni.h>
1920
#include <lib/support/CHIPJNIError.h>
2021
#include <lib/support/CodeUtils.h>
@@ -79,8 +80,17 @@ CHIP_ERROR JniReferences::GetClassRef(JNIEnv * env, const char * clsType, jclass
7980
CHIP_ERROR err = CHIP_NO_ERROR;
8081
jclass cls = nullptr;
8182

82-
cls = env->FindClass(clsType);
83-
env->ExceptionClear();
83+
// Try `j$/util/Optional` when enabling Java8.
84+
if (strcmp(clsType, "java/util/Optional") == 0)
85+
{
86+
cls = env->FindClass("j$/util/Optional");
87+
}
88+
89+
if (cls == nullptr)
90+
{
91+
env->ExceptionClear();
92+
cls = env->FindClass(clsType);
93+
}
8494

8595
if (cls == nullptr)
8696
{
@@ -121,6 +131,20 @@ CHIP_ERROR JniReferences::FindMethod(JNIEnv * env, jobject object, const char *
121131
VerifyOrReturnError(javaClass != nullptr, CHIP_JNI_ERROR_TYPE_NOT_FOUND);
122132

123133
*methodId = env->GetMethodID(javaClass, methodName, methodSignature);
134+
135+
// Try `j$` when enabling Java8.
136+
std::string methodSignature_java8_str(methodSignature);
137+
if (*methodId == nullptr && methodSignature_java8_str.find("java/util/Optional") != std::string::npos)
138+
{
139+
// Replace all "java/util/Optional" with "j$/util/Optional".
140+
while (methodSignature_java8_str.find("java/util/Optional") != std::string::npos)
141+
{
142+
size_t pos = methodSignature_java8_str.find("java/util/Optional");
143+
methodSignature_java8_str.replace(pos, strlen("java/util/Optional"), "j$/util/Optional");
144+
}
145+
*methodId = env->GetMethodID(javaClass, methodName, methodSignature_java8_str.c_str());
146+
}
147+
124148
VerifyOrReturnError(*methodId != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
125149

126150
return err;
@@ -193,6 +217,13 @@ CHIP_ERROR JniReferences::CreateOptional(jobject objectToWrap, jobject & outOpti
193217
chip::JniClass jniClass(optionalCls);
194218

195219
jmethodID ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Ljava/util/Optional;");
220+
221+
// Try `Lj$/util/Optional;` when enabling Java8.
222+
if (ofMethod == nullptr)
223+
{
224+
ofMethod = env->GetStaticMethodID(optionalCls, "ofNullable", "(Ljava/lang/Object;)Lj$/util/Optional;");
225+
}
226+
196227
VerifyOrReturnError(ofMethod != nullptr, CHIP_JNI_ERROR_METHOD_NOT_FOUND);
197228
outOptional = env->CallStaticObjectMethod(optionalCls, ofMethod, objectToWrap);
198229

0 commit comments

Comments
 (0)