Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qjniobject.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "qjniobject.h"
6
8
9#include <QtCore/qbytearray.h>
10#include <QtCore/qhash.h>
11#include <QtCore/qreadwritelock.h>
12#include <QtCore/qloggingcategory.h>
13
14
16
17Q_LOGGING_CATEGORY(lcJniThreadCheck, "qt.core.jni.threadcheck")
18
19using namespace Qt::StringLiterals;
20
21/*!
22 \class QJniObject
23 \inmodule QtCore
24 \since 6.1
25 \brief A convenience wrapper around the Java Native Interface (JNI).
26
27 The QJniObject class wraps a reference to a Java object, ensuring it isn't
28 garbage-collected and providing access to most \c JNIEnv method calls
29 (member, static) and fields (setter, getter). It eliminates much
30 boiler-plate that would normally be needed, with direct JNI access, for
31 every operation. Exceptions thrown by called Java methods are cleared by
32 default, but can since Qt 6.11 also be handled by the caller.
33
34 \note This API has been designed and tested for use with Android.
35 It has not been tested for other platforms.
36
37 \sa QJniEnvironment
38
39 \section1 Method Signatures
40
41 QJniObject provides convenience functions that will use the correct signature based on the
42 provided or deduced template arguments.
43
44 \code
45 jint x = QJniObject::callMethod<jint>("getSize");
46 QJniObject::callMethod<void>("touch");
47 jint ret = jString1.callMethod<jint>("compareToIgnoreCase", jString2.object<jstring>());
48 \endcode
49
50 These functions are variadic templates, and the compiler will deduce the
51 signature from the actual argument types. Only the return type needs to be
52 provided explicitly. QJniObject can deduce the signature string for
53 functions that take \l {JNI types}, and for types that have been declared
54 with the QtJniTypes type mapping.
55
56 \code
57 // Java class
58 package org.qtproject.qt;
59 class TestClass
60 {
61 static TestClass create() { ... }
62 static String fromNumber(int x) { ... }
63 static String[] stringArray(String s1, String s2) { ... }
64 }
65 \endcode
66
67 \code
68 // C++ code
69 Q_DECLARE_JNI_CLASS(TestClass, "org/qtproject/qt/TestClass")
70
71 // ...
72 using namespace QtJniTypes;
73 TestClass testClass = TestClass::callStaticMethod<TestClass>("create");
74 \endcode
75
76 This allows working with arbitrary Java and Android types in C++ code, without having to
77 create JNI signature strings explicitly.
78
79 \section2 Explicit JNI Signatures
80
81 It is possible to supply the signature yourself. In that case, it is important
82 that the signature matches the function you want to call.
83
84 \list
85 \li Class names need to be fully-qualified, for example: \c "java/lang/String".
86 \li Method signatures are written as \c "(ArgumentsTypes)ReturnType", see \l {JNI Types}.
87 \li All object types are returned as a QJniObject.
88 \endlist
89
90 The example below demonstrates how to call different static functions:
91
92 The signature structure is \c "(ArgumentsTypes)ReturnType". Array types in the signature
93 must have the \c {[} prefix, and the fully-qualified \c Object type names must have the
94 \c L prefix and the \c ; suffix. The signature for the \c create function is
95 \c {"()Lorg/qtproject/qt/TestClass;}. The signatures for the second and third functions
96 are \c {"(I)Ljava/lang/String;"} and
97 \c {"(Ljava/lang/String;Ljava/lang/String;)[Ljava/lang/String;"}, respectively.
98
99 We can call the \c create() function like this:
100
101 \code
102 // C++ code
103 QJniObject testClass = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass",
104 "create",
105 "()Lorg/qtproject/qt/TestClass;");
106 \endcode
107
108 For the second and third function we can rely on QJniObject's template methods to create
109 the implicit signature string, but we can also pass the signature string explicitly:
110
111 \code
112 // C++ code
113 QJniObject stringNumber = QJniObject::callStaticObjectMethod("org/qtproject/qt/TestClass",
114 "fromNumber",
115 "(I)Ljava/lang/String;", 10);
116 \endcode
117
118 For the implicit signature creation to work we need to specify the return type explicitly:
119
120 \code
121 // C++ code
122 QJniObject string1 = QJniObject::fromString("String1");
123 QJniObject string2 = QJniObject::fromString("String2");
124 QJniObject stringArray = QJniObject::callStaticObjectMethod<jobjectArray>(
125 "org/qtproject/qt/TestClass",
126 "stringArray",
127 string1.object<jstring>(),
128 string2.object<jstring>());
129 \endcode
130
131 Note that while the first template parameter specifies the return type of the Java
132 function, the method will still return a QJniObject.
133
134 \section1 Handling Java Exceptions
135
136 After calling Java functions that might throw exceptions, it is important
137 to check for, handle and clear out any exception before continuing. All
138 QJniObject functions can handle exceptions internally by reporting and
139 clearing them. This includes JNI exceptions, for instance when trying to
140 call a method that doesn't exist, or with bad parameters; and exceptions
141 are thrown by the method as a way of reporting errors or returning failure
142 information.
143
144 From Qt 6.11 on, client code can opt in to handle exceptions explicitly in
145 each call. To do so, use \c{std::expected} from C++ 23 as the return type,
146 with the value type as the expected, and \c{jthrowable} as the error type.
147 For instance, trying to read a setting value via the
148 \c{android.provider.Settings.Secure} type might throw an exception if the
149 setting does not exist.
150
151 \code
152 Q_DECLARE_JNI_CLASS(SettingsSecure, "android/provider/Settings$Secure")
153 using namespace QtJniTypes;
154
155 QString enabledInputMethods()
156 {
157 ContentResolver resolver;
158 SettingsSecure settings;
159
160 auto defaultInputMethods = settings.callMethod<std::expected<QString, jthrowable>>(
161 "getString", resolver, u"enabled_input_methods"_s
162 );
163 if (defaultInputMethods)
164 return defaultInputMethods.value();
165 QStringList stackTrace = QJniEnvironment::stackTrace(defaultInputMethods.error());
166 }
167 \endcode
168
169 You can use any other type that behaves like \c{std::expected}, so handling
170 exceptions explicitly is possible without using C++23. The only
171 requirements are that the type declares three nested types \c{value_type},
172 \c{error_type}, and \c{unexpected_type}, can be constructed from the value
173 type, and from its \c{unexpected_type} holding a \c{jthrowable}.
174
175 \note The user must handle exceptions manually when doing JNI calls using \c JNIEnv directly.
176 It is unsafe to make other JNI calls when exceptions are pending. For more information, see
177 QJniEnvironment::checkAndClearExceptions().
178
179 \section1 Java Native Methods
180
181 Java native methods makes it possible to call native code from Java, this is done by creating a
182 function declaration in Java and prefixing it with the \c native keyword.
183 Before a native function can be called from Java, you need to map the Java native function to a
184 native function in your code. Mapping functions can be done by calling
185 QJniEnvironment::registerNativeMethods().
186
187 The example below demonstrates how this could be done.
188
189 Java implementation:
190 \snippet jni/src_qjniobject.cpp Java native methods
191
192 C++ Implementation:
193 \snippet jni/src_qjniobject.cpp C++ native methods
194
195 \section1 The Lifetime of a Java Object
196
197 Most \l{Object types}{objects} received from Java will be local references
198 and will only stay valid until you return from the native method. After that,
199 the object becomes eligible for garbage collection. If your code creates
200 many local references in a loop you should delete them manually with each
201 iteration, otherwise you might run out of memory. For more information, see
202 \l {JNI Design Overview: Global and Local References}. Local references
203 created outside a native method scope must be deleted manually, since
204 the garbage collector will not free them automatically because we are using
205 \l {Java: AttachCurrentThread}{AttachCurrentThread}. For more information, see
206 \l {JNI tips: Local and global references}.
207
208 If you want to keep a Java object alive you need to either create a new global
209 reference to the object and release it when you are done, or construct a new
210 QJniObject and let it manage the lifetime of the Java object.
211
212 \sa object()
213
214 \note The QJniObject only manages its own references, if you construct a QJniObject from a
215 global or local reference that reference will not be released by the QJniObject.
216
217 \section1 JNI Types
218
219 \section2 Object Types
220 \table
221 \header
222 \li Type
223 \li Signature
224 \row
225 \li jobject
226 \li Ljava/lang/Object;
227 \row
228 \li jclass
229 \li Ljava/lang/Class;
230 \row
231 \li jstring
232 \li Ljava/lang/String;
233 \row
234 \li jthrowable
235 \li Ljava/lang/Throwable;
236 \row
237 \li jobjectArray
238 \li [Ljava/lang/Object;
239 \row
240 \li jarray
241 \li [\e<type>
242 \row
243 \li jbooleanArray
244 \li [Z
245 \row
246 \li jbyteArray
247 \li [B
248 \row
249 \li jcharArray
250 \li [C
251 \row
252 \li jshortArray
253 \li [S
254 \row
255 \li jintArray
256 \li [I
257 \row
258 \li jlongArray
259 \li [J
260 \row
261 \li jfloatArray
262 \li [F
263 \row
264 \li jdoubleArray
265 \li [D
266 \endtable
267
268 \section2 Primitive Types
269 \table
270 \header
271 \li Type
272 \li Signature
273 \row
274 \li jboolean
275 \li Z
276 \row
277 \li jbyte
278 \li B
279 \row
280 \li jchar
281 \li C
282 \row
283 \li jshort
284 \li S
285 \row
286 \li jint
287 \li I
288 \row
289 \li jlong
290 \li J
291 \row
292 \li jfloat
293 \li F
294 \row
295 \li jdouble
296 \li D
297 \endtable
298
299 \section2 Other
300 \table
301 \header
302 \li Type
303 \li Signature
304 \row
305 \li void
306 \li V
307 \row
308 \li \e{Custom type}
309 \li L\e<fully-qualified-name>;
310 \endtable
311
312 For more information about JNI, see \l {Java Native Interface Specification}.
313*/
314
315/*!
316 \fn bool operator==(const QJniObject &o1, const QJniObject &o2)
317
318 \relates QJniObject
319
320 Returns true if both objects, \a o1 and \a o2, are referencing the same Java object, or if both
321 are NULL. In any other cases false will be returned.
322*/
323
324/*!
325 \fn bool operator!=(const QJniObject &o1, const QJniObject &o2)
326 \relates QJniObject
327
328 Returns true if \a o1 holds a reference to a different object than \a o2.
329*/
330
331static bool isClassInstantiable(JNIEnv *env, const QByteArray &className, jclass clazz);
332static void throwInstantiationException(JNIEnv *env, QByteArray className, jclass clazz);
333
335{
336public:
338 {
339 }
341 JNIEnv *env = QJniEnvironment::getJniEnv();
342 if (m_jobject)
343 env->DeleteGlobalRef(m_jobject);
344 if (m_jclass && m_own_jclass)
345 env->DeleteGlobalRef(m_jclass);
346 }
347
348 template <typename ...Args>
349 void construct(const char *signature = nullptr, Args &&...args)
350 {
351 if (m_jclass) {
352 JNIEnv *env = QJniEnvironment::getJniEnv();
353 if (!isClassInstantiable(env, m_className, m_jclass)) {
354 throwInstantiationException(env, m_className, m_jclass);
355 return;
356 }
357 // get default constructor
358 jmethodID constructorId = QJniObject::getCachedMethodID(env, m_jclass, m_className, "<init>",
359 signature ? signature : "()V");
360 if (constructorId) {
361 jobject obj = nullptr;
362 if constexpr (sizeof...(Args) == 0)
363 obj = env->NewObject(m_jclass, constructorId);
364 else
365 obj = env->NewObjectV(m_jclass, constructorId, std::forward<Args>(args)...);
366 if (obj) {
367 m_jobject = env->NewGlobalRef(obj);
368 env->DeleteLocalRef(obj);
369 }
370 }
371 }
372 }
373
374 bool isJString(JNIEnv *env) const;
375
378 jclass m_jclass = nullptr;
379 bool m_own_jclass = true;
380 // Whether m_className is the name Qt resolved the class with.
381 bool m_resolvedByName = false;
382 enum class IsJString : quint8 {
386 };
388};
389
390// The separator keeps the concatenation unambiguous.
391template <typename ...Args>
392static inline QByteArray cacheKey(Args &&...args)
393{
394 return ((QByteArrayView(":") + QByteArrayView(args)) + ...);
395}
396
397struct JClass
398{
399 enum class Instantiable : quint8 { Unknown, Yes, No }; // Whether can call NewObject()
400
401 jclass clazz = nullptr;
403};
404
409Q_GLOBAL_STATIC(JClassHash, cachedClasses)
410Q_GLOBAL_STATIC(QReadWriteLock, cachedClassesLock)
411
412static jclass getCachedClass(const QByteArray &className)
413{
414 QReadLocker locker(cachedClassesLock);
415 const auto &it = cachedClasses->constFind(className);
416 return it != cachedClasses->constEnd() ? it.value().clazz : nullptr;
417}
418
419// NewObject() on an interface or an abstract class aborts the process
420// under CheckJNI, and leaves a pending InstantiationException otherwise.
421static bool queryInstantiable(JNIEnv *env, jclass clazz)
422{
423 jclass classClass = env->GetObjectClass(clazz);
424 const jmethodID getModifiers = env->GetMethodID(classClass, "getModifiers", "()I");
425 env->DeleteLocalRef(classClass);
426 // Class.getModifiers() cannot realistically be missing, but if we cannot
427 // tell then let the construction go ahead as it did before.
428 if (!getModifiers) {
429 QJniEnvironment::checkAndClearExceptions(env);
430 return true;
431 }
432 const jint modifiers = env->CallIntMethod(clazz, getModifiers);
433 if (QJniEnvironment::checkAndClearExceptions(env))
434 return true;
435
436 constexpr jint Interface = 0x00000200; // java.lang.reflect.Modifier.INTERFACE
437 constexpr jint Abstract = 0x00000400; // java.lang.reflect.Modifier.ABSTRACT
438 return !(modifiers & (Interface | Abstract));
439}
440
441static QByteArray classNameOf(JNIEnv *env, jclass clazz)
442{
443 jclass classClass = env->GetObjectClass(clazz);
444 const jmethodID getName = env->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
445 env->DeleteLocalRef(classClass);
446 if (!getName) {
447 QJniEnvironment::checkAndClearExceptions(env);
448 return QByteArray();
449 }
450 const auto name = static_cast<jstring>(env->CallObjectMethod(clazz, getName));
451 if (QJniEnvironment::checkAndClearExceptions(env))
452 return QByteArray();
453 const char *utf = env->GetStringUTFChars(name, nullptr);
454 const QByteArray result(utf, env->GetStringUTFLength(name));
455 env->ReleaseStringUTFChars(name, utf);
456 env->DeleteLocalRef(name);
457 return result;
458}
459
460// Matches what Class.newInstance() throws for the same class.
461static void throwInstantiationException(JNIEnv *env, QByteArray className, jclass clazz)
462{
463 if (className.isEmpty())
464 className = classNameOf(env, clazz);
465 jclass exceptionClass = env->FindClass("java/lang/InstantiationException");
466 if (!exceptionClass) {
467 QJniEnvironment::checkAndClearExceptions(env);
468 return;
469 }
470 const QByteArray message = className.replace('/', '.') + " cannot be instantiated";
471 env->ThrowNew(exceptionClass, message.constData());
472 env->DeleteLocalRef(exceptionClass);
473}
474
475// The answer is a property of the class, so pay for it once rather than on every construction.
476static bool isClassInstantiable(JNIEnv *env, const QByteArray &className, jclass clazz)
477{
478 if (className.isEmpty())
479 return queryInstantiable(env, clazz);
480
481 {
482 QReadLocker locker(cachedClassesLock);
483 const auto it = cachedClasses->constFind(className);
484 if (it != cachedClasses->constEnd() && it->instantiable != JClass::Instantiable::Unknown)
485 return it->instantiable == JClass::Instantiable::Yes;
486 }
487
488 const bool instantiable = queryInstantiable(env, clazz);
489 QWriteLocker locker(cachedClassesLock);
490 const auto it = cachedClasses->find(className);
491 if (it != cachedClasses->end())
492 it->instantiable = instantiable ? JClass::Instantiable::Yes : JClass::Instantiable::No;
493 return instantiable;
494}
495
496bool QJniObjectPrivate::isJString(JNIEnv *env) const
497{
498 Q_ASSERT(m_jobject);
499 if (m_is_jstring != IsJString::Unknown)
500 return m_is_jstring == IsJString::Yes;
501
502 static constexpr auto stringSignature = QtJniTypes::Traits<jstring>::className();
503 if (!m_className.isEmpty()) {
504 m_is_jstring = m_className == stringSignature
505 ? IsJString::Yes
506 : IsJString::No;
507 } else {
508 const jclass strClass = getCachedClass(stringSignature.data());
509 const bool isStringInstance = strClass
510 ? env->IsInstanceOf(m_jobject, strClass)
511 : false;
512 m_is_jstring = isStringInstance ? IsJString::Yes : IsJString::No;
513 }
514
515 return m_is_jstring == IsJString::Yes;
516}
517
518/*!
519 \internal
520
521 Get a JNI object from a jobject variant and do the necessary
522 exception clearing and delete the local reference before returning.
523 The JNI object can be null if there was an exception.
524*/
525static QJniObject getCleanJniObject(jobject object, JNIEnv *env)
526{
527 if (!object || env->ExceptionCheck())
528 return QJniObject();
529
530 return QJniObject::fromLocalRef(object);
531}
532
533namespace {
534
535jclass loadClassHelper(const QByteArray &className, JNIEnv *env)
536{
537 Q_ASSERT(env);
538 QByteArray classNameArray(className);
539#ifdef QT_DEBUG
540 if (classNameArray.contains('.'))
541 qWarning("QJniObject: className '%s' should use slash separators!", className.constData());
542#endif
543 classNameArray.replace('.', '/');
544 jclass clazz = getCachedClass(classNameArray);
545 if (clazz)
546 return clazz;
547
548 QWriteLocker locker(cachedClassesLock);
549 // Check again; another thread might have added the class to the cache after
550 // our call to getCachedClass and before we acquired the lock.
551 const auto &it = cachedClasses->constFind(classNameArray);
552 if (it != cachedClasses->constEnd())
553 return it.value().clazz;
554
555 // JNIEnv::FindClass wants "a fully-qualified class name or an array type signature"
556 // which is a slash-separated class name.
557 jclass localClazz = env->FindClass(classNameArray.constData());
558 if (localClazz) {
559 clazz = static_cast<jclass>(env->NewGlobalRef(localClazz));
560 env->DeleteLocalRef(localClazz);
561 } else {
562 // Clear the exception silently; we are going to try the ClassLoader next,
563 // so no need for warning unless that fails as well.
564 env->ExceptionClear();
565 }
566
567 if (!clazz) {
568 // Wrong class loader, try our own
569 jobject classLoader = QtAndroidPrivate::classLoader();
570 if (!classLoader)
571 return nullptr;
572
573 if (!cachedClasses->loadClassMethod) {
574 jclass classLoaderClass = env->GetObjectClass(classLoader);
575 if (!classLoaderClass)
576 return nullptr;
577 cachedClasses->loadClassMethod =
578 env->GetMethodID(classLoaderClass,
579 "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
580 env->DeleteLocalRef(classLoaderClass);
581 if (!cachedClasses->loadClassMethod) {
582 qCritical("Couldn't find the 'loadClass' method in the Qt class loader");
583 return nullptr;
584 }
585 }
586
587 // ClassLoader::loadClass on the other hand wants the binary name of the class,
588 // e.g. dot-separated. In testing it works also with /, but better to stick to
589 // the specification.
590 const QString binaryClassName = QString::fromLatin1(className).replace(u'/', u'.');
591 jstring classNameObject = env->NewString(binaryClassName.utf16(), binaryClassName.length());
592 jobject classObject = env->CallObjectMethod(classLoader,
593 cachedClasses->loadClassMethod,
594 classNameObject);
595 env->DeleteLocalRef(classNameObject);
596
597 if (classObject && !env->ExceptionCheck()) {
598 clazz = static_cast<jclass>(env->NewGlobalRef(classObject));
599 env->DeleteLocalRef(classObject);
600 }
601 // Clearing the exception is the caller's responsibility (see
602 // QtAndroidPrivate::findClass()) and QJniObject::loadClass{KeepExceptions}
603 }
604
605 if (clazz)
606 cachedClasses->insert(classNameArray, JClass{clazz});
607
608 return clazz;
609}
610
611} // unnamed namespace
612
613/*!
614 \internal
615 \a className must be slash-encoded
616*/
617jclass QtAndroidPrivate::findClass(const char *className, JNIEnv *env)
618{
619 jclass clazz = loadClassHelper(className, env);
620 if (!clazz)
621 QJniEnvironment::checkAndClearExceptions(env);
622 return clazz;
623}
624
625jclass QJniObject::loadClass(const QByteArray &className, JNIEnv *env)
626{
627 return QtAndroidPrivate::findClass(className, env);
628}
629
630jclass QJniObject::loadClassKeepExceptions(const QByteArray &className, JNIEnv *env)
631{
632 return loadClassHelper(className, env);
633}
634
635
636
637typedef QHash<QByteArray, jmethodID> JMethodIDHash;
638Q_GLOBAL_STATIC(JMethodIDHash, cachedMethodID)
639Q_GLOBAL_STATIC(QReadWriteLock, cachedMethodIDLock)
640
641jmethodID QJniObject::getMethodID(JNIEnv *env,
642 jclass clazz,
643 const char *name,
644 const char *signature,
645 bool isStatic)
646{
647 if (!clazz)
648 return nullptr;
649
650 jmethodID id = isStatic ? env->GetStaticMethodID(clazz, name, signature)
651 : env->GetMethodID(clazz, name, signature);
652
653 return id;
654}
655
656void QJniObject::callVoidMethodV(JNIEnv *env, jmethodID id, ...) const
657{
658 va_list args;
659 va_start(args, id);
660 env->CallVoidMethodV(d->m_jobject, id, args);
661 va_end(args);
662}
663
664jmethodID QJniObject::getCachedMethodID(JNIEnv *env,
665 jclass clazz,
666 const QByteArray &className,
667 const char *name,
668 const char *signature,
669 bool isStatic)
670{
671 if (className.isEmpty())
672 return getMethodID(env, clazz, name, signature, isStatic);
673
674 const QByteArray key = cacheKey(className, name, signature,
675 isStatic ? "static" : "instance");
676 QHash<QByteArray, jmethodID>::const_iterator it;
677
678 {
679 QReadLocker locker(cachedMethodIDLock);
680 it = cachedMethodID->constFind(key);
681 if (it != cachedMethodID->constEnd())
682 return it.value();
683 }
684
685 {
686 QWriteLocker locker(cachedMethodIDLock);
687 it = cachedMethodID->constFind(key);
688 if (it != cachedMethodID->constEnd())
689 return it.value();
690
691 jmethodID id = getMethodID(env, clazz, name, signature, isStatic);
692
693 if (id)
694 cachedMethodID->insert(key, id);
695 return id;
696 }
697}
698
699jmethodID QJniObject::getCachedMethodID(JNIEnv *env, const char *name,
700 const char *signature, bool isStatic) const
701{
702 // A class Qt did not resolve by name may share its name with another
703 // loader's, so it cannot share the name-keyed cache.
704 const QByteArray className = d->m_resolvedByName ? d->m_className : QByteArray();
705 return QJniObject::getCachedMethodID(env, d->m_jclass, className, name, signature, isStatic);
706}
707
708typedef QHash<QByteArray, jfieldID> JFieldIDHash;
709Q_GLOBAL_STATIC(JFieldIDHash, cachedFieldID)
710Q_GLOBAL_STATIC(QReadWriteLock, cachedFieldIDLock)
711
712jfieldID QJniObject::getFieldID(JNIEnv *env,
713 jclass clazz,
714 const char *name,
715 const char *signature,
716 bool isStatic)
717{
718 jfieldID id = isStatic ? env->GetStaticFieldID(clazz, name, signature)
719 : env->GetFieldID(clazz, name, signature);
720
721 return id;
722}
723
724jfieldID QJniObject::getCachedFieldID(JNIEnv *env,
725 jclass clazz,
726 const QByteArray &className,
727 const char *name,
728 const char *signature,
729 bool isStatic)
730{
731 if (className.isEmpty())
732 return getFieldID(env, clazz, name, signature, isStatic);
733
734 const QByteArray key = cacheKey(className, name, signature,
735 isStatic ? "static" : "instance");
736 QHash<QByteArray, jfieldID>::const_iterator it;
737
738 {
739 QReadLocker locker(cachedFieldIDLock);
740 it = cachedFieldID->constFind(key);
741 if (it != cachedFieldID->constEnd())
742 return it.value();
743 }
744
745 {
746 QWriteLocker locker(cachedFieldIDLock);
747 it = cachedFieldID->constFind(key);
748 if (it != cachedFieldID->constEnd())
749 return it.value();
750
751 jfieldID id = getFieldID(env, clazz, name, signature, isStatic);
752
753 if (id)
754 cachedFieldID->insert(key, id);
755 return id;
756 }
757}
758
759jfieldID QJniObject::getCachedFieldID(JNIEnv *env,
760 const char *name,
761 const char *signature,
762 bool isStatic) const
763{
764 const QByteArray className = d->m_resolvedByName ? d->m_className : QByteArray();
765 return QJniObject::getCachedFieldID(env, d->m_jclass, className, name, signature, isStatic);
766}
767
768/*!
769 \fn QJniObject::QJniObject()
770
771 Constructs an invalid JNI object.
772
773 \sa isValid()
774*/
775QJniObject::QJniObject()
776 : d(new QJniObjectPrivate())
777{
778}
779
780/*!
781 \fn QJniObject::QJniObject(const char *className)
782
783 Constructs a new JNI object by calling the default constructor of \a className.
784
785 \code
786 QJniObject myJavaString("java/lang/String");
787 \endcode
788*/
789QJniObject::QJniObject(const char *className)
790 : d(new QJniObjectPrivate())
791{
792 d->m_className = className;
793 d->m_jclass = loadClass(d->m_className, jniEnv());
794 d->m_own_jclass = false;
795 d->m_resolvedByName = true;
796
797 d->construct();
798 // Clear on a missing constructor, which would break the next JNI call.
799 if (!d->m_jobject)
800 QJniEnvironment::checkAndClearExceptions(jniEnv());
801}
802
803/*!
804 \fn QJniObject::QJniObject(const char *className, const char *signature, ...)
805
806 Constructs a new JNI object by calling the constructor of \a className with
807 \a signature specifying the types of any subsequent arguments.
808
809 \code
810 QJniEnvironment env;
811 char* str = "Hello";
812 jstring myJStringArg = env->NewStringUTF(str);
813 QJniObject myNewJavaString("java/lang/String", "(Ljava/lang/String;)V", myJStringArg);
814 \endcode
815*/
816QJniObject::QJniObject(const char *className, const char *signature, ...)
817 : d(new QJniObjectPrivate())
818{
819 d->m_className = className;
820 d->m_jclass = loadClass(d->m_className, jniEnv());
821 d->m_own_jclass = false;
822 d->m_resolvedByName = true;
823
824 va_list args;
825 va_start(args, signature);
826 d->construct(signature, args);
827 va_end(args);
828 // Clear on a missing constructor, which would break the next JNI call.
829 if (!d->m_jobject)
830 QJniEnvironment::checkAndClearExceptions(jniEnv());
831}
832
833/*!
834 \fn template<typename ...Args> QJniObject::QJniObject(const char *className, Args &&...args)
835 \since 6.4
836
837 Constructs a new JNI object by calling the constructor of \a className with
838 the arguments \a args. This constructor is only available if all \a args are
839 known \l {JNI Types}.
840
841 \code
842 QJniEnvironment env;
843 char* str = "Hello";
844 jstring myJStringArg = env->NewStringUTF(str);
845 QJniObject myNewJavaString("java/lang/String", myJStringArg);
846 \endcode
847*/
848
849/*!
850 Constructs a new JNI object from \a clazz by calling the constructor with
851 \a signature specifying the types of any subsequent arguments.
852
853 \code
854 QJniEnvironment env;
855 jclass myClazz = env.findClass("org/qtproject/qt/TestClass");
856 QJniObject(myClazz, "(I)V", 3);
857 \endcode
858*/
859QJniObject::QJniObject(jclass clazz, const char *signature, ...)
860 : d(new QJniObjectPrivate())
861{
862 if (clazz) {
863 d->m_jclass = static_cast<jclass>(jniEnv()->NewGlobalRef(clazz));
864 va_list args;
865 va_start(args, signature);
866 d->construct(signature, args);
867 va_end(args);
868 }
869}
870
871/*!
872 \fn template<typename ...Args> QJniObject::QJniObject(jclass clazz, Args &&...args)
873 \since 6.4
874
875 Constructs a new JNI object from \a clazz by calling the constructor with
876 the arguments \a args. This constructor is only available if all \a args are
877 known \l {JNI Types}.
878
879 \code
880 QJniEnvironment env;
881 jclass myClazz = env.findClass("org/qtproject/qt/TestClass");
882 QJniObject(myClazz, 3);
883 \endcode
884*/
885
886/*!
887 Constructs a new JNI object by calling the default constructor of \a clazz.
888
889 \note The QJniObject will create a new reference to the class \a clazz
890 and releases it again when it is destroyed. References to the class created
891 outside the QJniObject need to be managed by the caller.
892*/
893
894QJniObject::QJniObject(jclass clazz)
895 : QJniObject(clazz, "()V")
896{
897}
898
899/*!
900 Constructs a new JNI object around the Java object \a object.
901
902 \note The QJniObject will hold a reference to the Java object \a object
903 and release it when destroyed. Any references to the Java object \a object
904 outside QJniObject needs to be managed by the caller. In most cases you
905 should never call this function with a local reference unless you intend
906 to manage the local reference yourself. See QJniObject::fromLocalRef()
907 for converting a local reference to a QJniObject.
908
909 \sa fromLocalRef()
910*/
911QJniObject::QJniObject(jobject object)
912 : d(new QJniObjectPrivate())
913{
914 if (!object)
915 return;
916
917 JNIEnv *env = jniEnv();
918 d->m_jobject = env->NewGlobalRef(object);
919 jclass cls = env->GetObjectClass(object);
920 d->m_jclass = static_cast<jclass>(env->NewGlobalRef(cls));
921 env->DeleteLocalRef(cls);
922}
923
924/*!
925 \fn template<typename Class, typename ...Args> static inline QJniObject QJniObject::construct(Args &&...args)
926 \since 6.4
927
928 Constructs an instance of the Java class that is the equivalent of \c Class and
929 returns a QJniObject containing the JNI object. The arguments in \a args are
930 passed to the Java constructor.
931
932 \code
933 QJniObject javaString = QJniObject::construct<jstring>();
934 \endcode
935
936 This function is only available if all \a args are known \l {JNI Types}.
937*/
938
939/*!
940 \fn QJniObject::~QJniObject()
941
942 Destroys the JNI object and releases any references held by the JNI object.
943*/
944QJniObject::~QJniObject()
945{}
946
947/*!
948 \fn void QJniObject::swap(QJniObject &other)
949 \since 6.8
950 \memberswap{object}
951*/
952
953
954namespace {
955QByteArray getClassNameHelper(JNIEnv *env, const QJniObjectPrivate *d)
956{
957 if (env->PushLocalFrame(3) != JNI_OK) // JVM out of memory
958 return QByteArray();
959
960 jmethodID mid = env->GetMethodID(d->m_jclass, "getClass", "()Ljava/lang/Class;");
961 jobject classObject = env->CallObjectMethod(d->m_jobject, mid);
962 jclass classObjectClass = env->GetObjectClass(classObject);
963 mid = env->GetMethodID(classObjectClass, "getName", "()Ljava/lang/String;");
964 jstring stringObject = static_cast<jstring>(env->CallObjectMethod(classObject, mid));
965 const jsize length = env->GetStringUTFLength(stringObject);
966 const char* nameString = env->GetStringUTFChars(stringObject, NULL);
967 const QByteArray result = QByteArray::fromRawData(nameString, length).replace('.', '/');
968 env->ReleaseStringUTFChars(stringObject, nameString);
969 env->PopLocalFrame(nullptr);
970 return result;
971}
972}
973
974/*! \internal
975
976 Returns the JNIEnv of the calling thread.
977*/
978JNIEnv *QJniObject::jniEnv() const noexcept
979{
980 return QJniEnvironment::getJniEnv();
981}
982
983/*!
984 \fn jobject QJniObject::object() const
985 \fn template <typename T> T QJniObject::object() const
986
987 Returns the object held by the QJniObject either as jobject or as type T.
988 T can be one of \l {Object Types}{JNI Object Types}.
989
990 \code
991 QJniObject string = QJniObject::fromString("Hello, JNI");
992 jstring jstring = string.object<jstring>();
993 \endcode
994
995 \note The returned object is still kept alive by this QJniObject. To keep the
996 object alive beyond the lifetime of this QJniObject, for example to record it
997 for later use, the easiest approach is to store it in another QJniObject with
998 a suitable lifetime. Alternatively, you may create a new global reference to the
999 object and store it, taking care to free it when you are done with it.
1000
1001 \snippet jni/src_qjniobject.cpp QJniObject scope
1002*/
1003jobject QJniObject::object() const
1004{
1005 return javaObject();
1006}
1007
1008/*!
1009 \fn jclass QJniObject::objectClass() const
1010
1011 Returns the class object held by the QJniObject as a \c jclass.
1012
1013 \note The returned object is still kept alive by this QJniObject. To keep the
1014 object alive beyond the lifetime of this QJniObject, for example to record it
1015 for later use, the easiest approach is to store it in another QJniObject with
1016 a suitable lifetime. Alternatively, you may create a new global reference to the
1017 object and store it, taking care to free it when you are done with it.
1018
1019 \since 6.2
1020*/
1021jclass QJniObject::objectClass() const
1022{
1023 return d->m_jclass;
1024}
1025
1026/*!
1027 \since 6.13
1028
1029 Returns true if the object held by this QJniObject is an instance of \a clazz,
1030 or of a class that extends or implements it; otherwise returns false.
1031
1032 Returns false if this QJniObject is not \l{isValid()}{valid}, or if \a clazz
1033 is \nullptr.
1034
1035 \sa {QJniObject::}{isInstanceOf(const char *className)}
1036*/
1037bool QJniObject::isInstanceOf(jclass clazz) const
1038{
1039 if (!clazz || !isValid())
1040 return false;
1041 return jniEnv()->IsInstanceOf(d->m_jobject, clazz);
1042}
1043
1044/*!
1045 \since 6.13
1046 \overload
1047
1048 Returns true if the object held by this QJniObject is an instance of the class
1049 \a className, or of a class that extends or implements it; otherwise returns
1050 false.
1051
1052 \a className must be a fully-qualified class name using slashes as separators,
1053 for example \c {"java/lang/CharSequence"}. Returns false if the class cannot be
1054 found.
1055
1056 \code
1057 QJniObject activity = QtAndroidPrivate::activity();
1058 if (activity.isInstanceOf("org/qtproject/qt/android/QtActivityBase"))
1059 qDebug("Qt owns this activity");
1060 \endcode
1061
1062 If the class is declared with Q_DECLARE_JNI_CLASS, prefer the template
1063 overload, which resolves the name at compile time.
1064
1065 \code
1066 if (activity.isInstanceOf<QtJniTypes::QtActivityBase>())
1067 qDebug("Qt owns this activity");
1068 \endcode
1069*/
1070bool QJniObject::isInstanceOf(const char *className) const
1071{
1072 if (!isValid())
1073 return false;
1074 JNIEnv *env = jniEnv();
1075 // findClass() caches, so repeated queries do not pay for the lookup.
1076 jclass clazz = QtAndroidPrivate::findClass(className, env);
1077 return clazz && env->IsInstanceOf(d->m_jobject, clazz);
1078}
1079
1080/*!
1081 \fn template <typename Class> bool QJniObject::isInstanceOf() const
1082 \since 6.13
1083
1084 Returns true if the object held by this QJniObject is an instance of \c Class,
1085 or of a class that extends or implements it; otherwise returns false.
1086
1087 \c Class needs to be declared with Q_DECLARE_JNI_CLASS, so that the class name
1088 is known at compile time.
1089*/
1090
1091/*!
1092 \fn QByteArray QJniObject::className() const
1093
1094 Returns the name of the class object held by the QJniObject as a \c QByteArray.
1095
1096 \since 6.2
1097*/
1098QByteArray QJniObject::className() const
1099{
1100 if (d->m_className.isEmpty() && d->m_jclass && d->m_jobject) {
1101 JNIEnv *env = jniEnv();
1102 d->m_className = getClassNameHelper(env, d.get());
1103 }
1104 return d->m_className;
1105}
1106
1107/*!
1108 \fn template <typename Ret, typename ...Args> auto QJniObject::callMethod(const char *methodName, const char *signature, Args &&...args) const
1109 \since 6.4
1110
1111 Calls the object's method \a methodName with \a signature specifying the types of any
1112 subsequent arguments \a args, and returns the value (unless Ret is \c void). If Ret
1113 is a jobject type, then the returned value will be a QJniObject.
1114
1115 \code
1116 QJniObject myJavaString("org/qtproject/qt/TestClass");
1117 jint index = myJavaString.callMethod<jint>("indexOf", "(I)I", 0x0051);
1118 \endcode
1119*/
1120
1121/*!
1122 \fn template <typename Ret, typename ...Args> auto QJniObject::callMethod(const char *methodName, Args &&...args) const
1123 \since 6.4
1124
1125 Calls the method \a methodName with arguments \a args and returns the value
1126 (unless Ret is \c void). If Ret is a jobject type, then the returned value
1127 will be a QJniObject.
1128
1129 \code
1130 QJniObject myJavaString("org/qtproject/qt/TestClass");
1131 jint size = myJavaString.callMethod<jint>("length");
1132 \endcode
1133
1134 The method signature is deduced at compile time from Ret and the types
1135 of \a args. Ret can be a \c{std::expected}-compatible type that returns
1136 a value, or \l{Handling Java Exceptions}{any Java exception thrown} by the
1137 called method.
1138*/
1139
1140/*!
1141 \fn template <typename Ret, typename ...Args> auto QJniObject::callStaticMethod(const char *className, const char *methodName, const char *signature, Args &&...args)
1142 \since 6.4
1143
1144 Calls the static method \a methodName from class \a className with \a signature
1145 specifying the types of any subsequent arguments \a args. Returns the result of
1146 the method (unless Ret is \c void). If Ret is a jobject type, then the
1147 returned value will be a QJniObject.
1148
1149 \code
1150 jint a = 2;
1151 jint b = 4;
1152 jint max = QJniObject::callStaticMethod<jint>("java/lang/Math", "max", "(II)I", a, b);
1153 \endcode
1154*/
1155
1156/*!
1157 \fn template <typename Ret, typename ...Args> auto QJniObject::callStaticMethod(const char *className, const char *methodName, Args &&...args)
1158 \since 6.4
1159
1160 Calls the static method \a methodName on class \a className with arguments \a args,
1161 and returns the value of type Ret (unless Ret is \c void). If Ret
1162 is a jobject type, then the returned value will be a QJniObject.
1163
1164 \code
1165 jint value = QJniObject::callStaticMethod<jint>("MyClass", "staticMethod");
1166 \endcode
1167
1168 The method signature is deduced at compile time from Ret and the types
1169 of \a args. Ret can be a \c{std::expected}-compatible type that returns
1170 a value, or \l{Handling Java Exceptions}{any Java exception thrown} by the
1171 called method.
1172*/
1173
1174/*!
1175 \fn template <typename Ret, typename ...Args> auto QJniObject::callStaticMethod(jclass clazz, const char *methodName, const char *signature, Args &&...args)
1176
1177 Calls the static method \a methodName from \a clazz with \a signature
1178 specifying the types of any subsequent arguments. Returns the result of
1179 the method (unless Ret is \c void). If Ret is a jobject type, then the
1180 returned value will be a QJniObject.
1181
1182 \code
1183 QJniEnvironment env;
1184 jclass javaMathClass = env.findClass("java/lang/Math");
1185 jint a = 2;
1186 jint b = 4;
1187 jint max = QJniObject::callStaticMethod<jint>(javaMathClass, "max", "(II)I", a, b);
1188 \endcode
1189*/
1190
1191/*!
1192 \fn template <typename Ret, typename ...Args> auto QJniObject::callStaticMethod(jclass clazz, jmethodID methodId, Args &&...args)
1193 \since 6.4
1194
1195 Calls the static method identified by \a methodId from the class \a clazz
1196 with any subsequent arguments, and returns the value of type Ret (unless
1197 Ret is \c void). If Ret is a jobject type, then the returned value will
1198 be a QJniObject.
1199
1200 Useful when \a clazz and \a methodId are already cached from previous operations.
1201
1202 \code
1203 QJniEnvironment env;
1204 jclass javaMathClass = env.findClass("java/lang/Math");
1205 jmethodID methodId = env.findStaticMethod(javaMathClass, "max", "(II)I");
1206 if (methodId != 0) {
1207 jint a = 2;
1208 jint b = 4;
1209 jint max = QJniObject::callStaticMethod<jint>(javaMathClass, methodId, a, b);
1210 }
1211 \endcode
1212*/
1213
1214/*!
1215 \fn template <typename Ret, typename ...Args> auto QJniObject::callStaticMethod(jclass clazz, const char *methodName, Args &&...args)
1216 \since 6.4
1217
1218 Calls the static method \a methodName on \a clazz and returns the value of type Ret
1219 (unless Ret is \c void). If Ret is a jobject type, then the returned value will
1220 be a QJniObject.
1221
1222 \code
1223 QJniEnvironment env;
1224 jclass javaMathClass = env.findClass("java/lang/Math");
1225 jdouble randNr = QJniObject::callStaticMethod<jdouble>(javaMathClass, "random");
1226 \endcode
1227
1228 The method signature is deduced at compile time from Ret and the types
1229 of \a args. Ret can be a \c{std::expected}-compatible type that returns
1230 a value, or \l{Handling Java Exceptions}{any Java exception thrown} by the
1231 called method.
1232*/
1233
1234/*!
1235 \fn template <typename Klass, typename Ret, typename ...Args> auto QJniObject::callStaticMethod(const char *methodName, Args &&...args)
1236 \since 6.7
1237
1238 Calls the static method \a methodName on the class \c Klass and returns the value of type
1239 Ret (unless Ret is \c void). If Ret is a jobject type, then the returned value will
1240 be a QJniObject.
1241
1242 The method signature is deduced at compile time from Ret and the types
1243 of \a args. \c Klass needs to be a C++ type with a registered type mapping
1244 to a Java type. Ret can be a \c{std::expected}-compatible type that
1245 returns a value, or \l{Handling Java Exceptions}{any Java exception thrown}
1246 by the called method.
1247
1248*/
1249
1250/*!
1251 \fn QJniObject QJniObject::callObjectMethod(const char *methodName, const char *signature, ...) const
1252
1253 Calls the Java object's method \a methodName with \a signature specifying
1254 the types of any subsequent arguments.
1255
1256 \code
1257 QJniObject myJavaString = QJniObject::fromString("Hello, Java");
1258 QJniObject mySubstring = myJavaString.callObjectMethod("substring",
1259 "(II)Ljava/lang/String;", 7, 11);
1260 \endcode
1261*/
1262QJniObject QJniObject::callObjectMethod(const char *methodName, const char *signature, ...) const
1263{
1264 JNIEnv *env = jniEnv();
1265 jmethodID id = getCachedMethodID(env, methodName, signature);
1266 va_list args;
1267 va_start(args, signature);
1268 // can't go back from variadic arguments to variadic templates
1269 jobject object = id ? jniEnv()->CallObjectMethodV(javaObject(), id, args) : nullptr;
1270 QJniObject res = getCleanJniObject(object, env);
1271 va_end(args);
1272
1273 QJniEnvironment::checkAndClearExceptions(env);
1274 return res;
1275}
1276
1277/*!
1278 \fn QJniObject QJniObject::callStaticObjectMethod(const char *className, const char *methodName, const char *signature, ...)
1279
1280 Calls the static method \a methodName from the class \a className with \a signature
1281 specifying the types of any subsequent arguments.
1282
1283 \code
1284 QJniObject thread = QJniObject::callStaticObjectMethod("java/lang/Thread", "currentThread",
1285 "()Ljava/lang/Thread;");
1286 QJniObject string = QJniObject::callStaticObjectMethod("java/lang/String", "valueOf",
1287 "(I)Ljava/lang/String;", 10);
1288 \endcode
1289*/
1290QJniObject QJniObject::callStaticObjectMethod(const char *className, const char *methodName,
1291 const char *signature, ...)
1292{
1293 JNIEnv *env = QJniEnvironment::getJniEnv();
1294 jclass clazz = QJniObject::loadClass(className, env);
1295 if (clazz) {
1296 jmethodID id = QJniObject::getCachedMethodID(env, clazz,
1297 className,
1298 methodName, signature, true);
1299 if (id) {
1300 va_list args;
1301 va_start(args, signature);
1302 QJniObject res = getCleanJniObject(env->CallStaticObjectMethodV(clazz, id, args), env);
1303 va_end(args);
1304 return res;
1305 }
1306 }
1307
1308 return QJniObject();
1309}
1310
1311/*!
1312 \fn QJniObject QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName, const char *signature, ...)
1313
1314 Calls the static method \a methodName from class \a clazz with \a signature
1315 specifying the types of any subsequent arguments.
1316*/
1317QJniObject QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName,
1318 const char *signature, ...)
1319{
1320 if (clazz) {
1321 QJniEnvironment env;
1322 jmethodID id = getMethodID(env.jniEnv(), clazz, methodName, signature, true);
1323 if (id) {
1324 va_list args;
1325 va_start(args, signature);
1326 QJniObject res = getCleanJniObject(env->CallStaticObjectMethodV(clazz, id, args), env.jniEnv());
1327 va_end(args);
1328 return res;
1329 }
1330 }
1331
1332 return QJniObject();
1333}
1334
1335/*!
1336 \fn QJniObject QJniObject::callStaticObjectMethod(jclass clazz, jmethodID methodId, ...)
1337
1338 Calls the static method identified by \a methodId from the class \a clazz
1339 with any subsequent arguments. Useful when \a clazz and \a methodId are
1340 already cached from previous operations.
1341
1342 \code
1343 QJniEnvironment env;
1344 jclass clazz = env.findClass("java/lang/String");
1345 jmethodID methodId = env.findStaticMethod(clazz, "valueOf", "(I)Ljava/lang/String;");
1346 if (methodId != 0)
1347 QJniObject str = QJniObject::callStaticObjectMethod(clazz, methodId, 10);
1348 \endcode
1349*/
1350QJniObject QJniObject::callStaticObjectMethod(jclass clazz, jmethodID methodId, ...)
1351{
1352 if (clazz && methodId) {
1353 JNIEnv *env = QJniEnvironment::getJniEnv();
1354 va_list args;
1355 va_start(args, methodId);
1356 QJniObject res = getCleanJniObject(env->CallStaticObjectMethodV(clazz, methodId, args), env);
1357 va_end(args);
1358 return res;
1359 }
1360
1361 return QJniObject();
1362}
1363
1364/*!
1365 \fn template<typename Ret, typename ...Args> QJniObject QJniObject::callObjectMethod(const char *methodName, Args &&...args) const
1366 \since 6.4
1367
1368 Calls the Java objects method \a methodName with arguments \a args and returns a
1369 new QJniObject for the returned Java object.
1370
1371 \code
1372 QJniObject myJavaString = QJniObject::fromString("Hello, Java");
1373 QJniObject myJavaString2 = myJavaString1.callObjectMethod<jstring>("toString");
1374 \endcode
1375
1376 The method signature is deduced at compile time from Ret and the types
1377 of \a args. Ret can be a \c{std::expected}-compatible type that returns
1378 a value, or \l{Handling Java Exceptions}{any Java exception thrown} by the
1379 called method.
1380*/
1381
1382/*!
1383 \fn template<typename Ret, typename ...Args> QJniObject QJniObject::callStaticObjectMethod(const char *className, const char *methodName, Args &&...args)
1384 \since 6.4
1385
1386 Calls the static method with \a methodName on the class \a className, passing
1387 arguments \a args, and returns a new QJniObject for the returned Java object.
1388
1389 \code
1390 QJniObject string = QJniObject::callStaticObjectMethod<jstring>("CustomClass", "getClassName");
1391 \endcode
1392
1393 The method signature is deduced at compile time from Ret and the types
1394 of \a args. Ret can be a \c{std::expected}-compatible type that returns
1395 a value, or \l{Handling Java Exceptions}{any Java exception thrown} by the
1396 called method.
1397*/
1398
1399/*!
1400 \fn template<typename Ret, typename ...Args> QJniObject QJniObject::callStaticObjectMethod(jclass clazz, const char *methodName, Args &&...args)
1401 \since 6.4
1402
1403 Calls the static method with \a methodName on \a clazz, passing arguments \a args,
1404 and returns a new QJniObject for the returned Java object.
1405*/
1406
1407/*!
1408 \fn template <typename T, std::enable_if_t<std::is_convertible_v<T, jobject>, bool> = true> QJniObject &QJniObject::operator=(T object)
1409
1410 Replace the current object with \a object. The old Java object will be released.
1411*/
1412
1413/*!
1414 \fn template <typename Ret, typename Type> auto QJniObject::setStaticField(const char *className, const char *fieldName, const char *signature, Type value);
1415
1416 Sets the static field \a fieldName on the class \a className to \a value
1417 using the setter with \a signature.
1418
1419*/
1420
1421/*!
1422 \fn template <typename Ret, typename Type> auto QJniObject::setStaticField(jclass clazz, const char *fieldName, const char *signature, Type value);
1423
1424 Sets the static field \a fieldName on the class \a clazz to \a value using
1425 the setter with \a signature.
1426*/
1427
1428/*!
1429 \fn template<typename T> T QJniObject::getField(const char *fieldName) const
1430
1431 Retrieves the value of the field \a fieldName.
1432
1433 \code
1434 QJniObject volumeControl("org/qtproject/qt/TestClass");
1435 jint fieldValue = volumeControl.getField<jint>("FIELD_NAME");
1436 \endcode
1437*/
1438
1439/*!
1440 \fn template<typename T> T QJniObject::getStaticField(const char *className, const char *fieldName)
1441
1442 Retrieves the value from the static field \a fieldName on the class \a className.
1443*/
1444
1445/*!
1446 \fn template<typename T> T QJniObject::getStaticField(jclass clazz, const char *fieldName)
1447
1448 Retrieves the value from the static field \a fieldName on \a clazz.
1449*/
1450
1451/*!
1452 \fn template <typename Klass, typename T> auto QJniObject::getStaticField(const char *fieldName)
1453
1454 Retrieves the value from the static field \a fieldName for the class \c Klass.
1455
1456 \c Klass needs to be a C++ type with a registered type mapping to a Java type.
1457*/
1458
1459/*!
1460 \fn template <typename Ret, typename Type> auto QJniObject::setStaticField(const char *className, const char *fieldName, Type value)
1461
1462 Sets the static field \a fieldName of the class \a className to \a value.
1463*/
1464
1465/*!
1466 \fn template <typename Ret, typename Type> auto QJniObject::setStaticField(jclass clazz, const char *fieldName, Type value)
1467
1468 Sets the static field \a fieldName of the class \a clazz to \a value.
1469*/
1470
1471/*!
1472 \fn template <typename Klass, typename Ret, typename Type> auto QJniObject::setStaticField(const char *fieldName, Type value)
1473
1474 Sets the static field \a fieldName of the class \c Klass to \a value.
1475
1476 \c Klass needs to be a C++ type with a registered type mapping to a Java type.
1477*/
1478
1479/*!
1480 \fn QJniObject QJniObject::getStaticObjectField(const char *className, const char *fieldName, const char *signature)
1481
1482 Retrieves a JNI object from the field \a fieldName with \a signature from
1483 class \a className.
1484
1485 \note This function can be used without a template type.
1486
1487 \code
1488 QJniObject jobj = QJniObject::getStaticObjectField("class/with/Fields", "FIELD_NAME",
1489 "Ljava/lang/String;");
1490 \endcode
1491*/
1492QJniObject QJniObject::getStaticObjectField(const char *className,
1493 const char *fieldName,
1494 const char *signature)
1495{
1496 JNIEnv *env = QJniEnvironment::getJniEnv();
1497 jclass clazz = QJniObject::loadClass(className, env);
1498 if (!clazz)
1499 return QJniObject();
1500 jfieldID id = QJniObject::getCachedFieldID(env, clazz,
1501 className,
1502 fieldName,
1503 signature, true);
1504 if (!id)
1505 return QJniObject();
1506
1507 return getCleanJniObject(env->GetStaticObjectField(clazz, id), env);
1508}
1509
1510/*!
1511 \fn QJniObject QJniObject::getStaticObjectField(jclass clazz, const char *fieldName, const char *signature)
1512
1513 Retrieves a JNI object from the field \a fieldName with \a signature from
1514 class \a clazz.
1515
1516 \note This function can be used without a template type.
1517
1518 \code
1519 QJniObject jobj = QJniObject::getStaticObjectField(clazz, "FIELD_NAME", "Ljava/lang/String;");
1520 \endcode
1521*/
1522QJniObject QJniObject::getStaticObjectField(jclass clazz, const char *fieldName,
1523 const char *signature)
1524{
1525 JNIEnv *env = QJniEnvironment::getJniEnv();
1526 jfieldID id = getFieldID(env, clazz, fieldName, signature, true);
1527
1528 const auto clearExceptions = qScopeGuard([env]{
1529 QJniEnvironment::checkAndClearExceptions(env);
1530 });
1531
1532 return getCleanJniObject(getStaticObjectFieldImpl(env, clazz, id), env);
1533}
1534
1535/*!
1536 \fn template <typename Ret, typename Type> void QJniObject::setField(const char *fieldName, const char *signature, Type value)
1537
1538 Sets the value of \a fieldName with \a signature to \a value.
1539
1540 \code
1541 QJniObject stringArray = ...;
1542 QJniObject obj = ...;
1543 obj.setObjectField<jobjectArray>("KEY_VALUES", "([Ljava/lang/String;)V",
1544 stringArray.object<jobjectArray>())
1545 \endcode
1546*/
1547
1548/*!
1549 \fn template<typename T> QJniObject QJniObject::getObjectField(const char *fieldName) const
1550
1551 Retrieves a JNI object from the field \a fieldName.
1552
1553 \code
1554 QJniObject field = jniObject.getObjectField<jstring>("FIELD_NAME");
1555 \endcode
1556*/
1557
1558/*!
1559 \fn QJniObject QJniObject::getObjectField(const char *fieldName, const char *signature) const
1560
1561 Retrieves a JNI object from the field \a fieldName with \a signature.
1562
1563 \note This function can be used without a template type.
1564
1565 \code
1566 QJniObject field = jniObject.getObjectField("FIELD_NAME", "Ljava/lang/String;");
1567 \endcode
1568*/
1569QJniObject QJniObject::getObjectField(const char *fieldName, const char *signature) const
1570{
1571 JNIEnv *env = jniEnv();
1572 jfieldID id = getCachedFieldID(env, fieldName, signature);
1573
1574 const auto clearExceptions = qScopeGuard([env]{
1575 QJniEnvironment::checkAndClearExceptions(env);
1576 });
1577
1578 return getCleanJniObject(getObjectFieldImpl(env, id), env);
1579}
1580
1581/*!
1582 \fn template <typename Ret, typename Type> void QJniObject::setField(const char *fieldName, Type value)
1583
1584 Sets the value of \a fieldName to \a value.
1585
1586 \code
1587 QJniObject obj;
1588 obj.setField<jint>("AN_INT_FIELD", 10);
1589 jstring myString = ...;
1590 obj.setField<jstring>("A_STRING_FIELD", myString);
1591 \endcode
1592*/
1593
1594/*!
1595 \fn template<typename T> QJniObject QJniObject::getStaticObjectField(const char *className, const char *fieldName)
1596
1597 Retrieves the object from the field \a fieldName on the class \a className.
1598
1599 \code
1600 QJniObject jobj = QJniObject::getStaticObjectField<jstring>("class/with/Fields", "FIELD_NAME");
1601 \endcode
1602*/
1603
1604/*!
1605 \fn template<typename T> QJniObject QJniObject::getStaticObjectField(jclass clazz, const char *fieldName)
1606
1607 Retrieves the object from the field \a fieldName on \a clazz.
1608
1609 \code
1610 QJniObject jobj = QJniObject::getStaticObjectField<jstring>(clazz, "FIELD_NAME");
1611 \endcode
1612*/
1613
1614/*!
1615 \fn QJniObject QJniObject::fromString(const QString &string)
1616
1617 Creates a Java string from the QString \a string and returns a QJniObject holding that string.
1618
1619 \code
1620 QString myQString = "QString";
1621 QJniObject myJavaString = QJniObject::fromString(myQString);
1622 \endcode
1623
1624 \sa toString()
1625*/
1626QJniObject QJniObject::fromString(const QString &string)
1627{
1628 JNIEnv *env = QJniEnvironment::getJniEnv();
1629 jstring stringRef = QtJniTypes::Detail::fromQString(string, env);
1630 QJniObject stringObject = getCleanJniObject(stringRef, env);
1631 stringObject.d->m_className = QtJniTypes::Traits<jstring>::className();
1632 stringObject.d->m_resolvedByName = true;
1633 stringObject.d->m_is_jstring = QJniObjectPrivate::IsJString::Yes;
1634 return stringObject;
1635}
1636
1637/*!
1638 \fn QString QJniObject::toString() const
1639
1640 Returns a QString with a string representation of the java object.
1641 Calling this function on a Java String object is a convenient way of getting the actual string
1642 data.
1643
1644 \code
1645 QJniObject string = ...; // "Hello Java"
1646 QString qstring = string.toString(); // "Hello Java"
1647 \endcode
1648
1649 \sa fromString()
1650*/
1651QString QJniObject::toString() const
1652{
1653 if (!isValid())
1654 return QString();
1655
1656 JNIEnv *env = jniEnv();
1657 if (d->isJString(env))
1658 return QtJniTypes::Detail::toQString(object<jstring>(), env);
1659
1660 const QJniObject string = callMethod<jstring>("toString");
1661 return QtJniTypes::Detail::toQString(string.object<jstring>(), env);
1662}
1663
1664/*!
1665 \fn bool QJniObject::isClassAvailable(const char *className)
1666
1667 Returns true if the Java class \a className is available.
1668
1669 \code
1670 if (QJniObject::isClassAvailable("java/lang/String")) {
1671 // condition statement
1672 }
1673 \endcode
1674*/
1675bool QJniObject::isClassAvailable(const char *className)
1676{
1677 JNIEnv *env = QJniEnvironment::getJniEnv();
1678
1679 if (!env)
1680 return false;
1681
1682 return loadClass(className, env);
1683}
1684
1685/*!
1686 \fn bool QJniObject::isValid() const
1687
1688 Returns true if this instance holds a valid Java object.
1689
1690 \code
1691 QJniObject qjniObject; // ==> isValid() == false
1692 QJniObject qjniObject(0) // ==> isValid() == false
1693 QJniObject qjniObject("could/not/find/Class") // ==> isValid() == false
1694 \endcode
1695*/
1696bool QJniObject::isValid() const
1697{
1698 return d && d->m_jobject;
1699}
1700
1701/*!
1702 \fn QJniObject QJniObject::fromLocalRef(jobject localRef)
1703
1704 Creates a QJniObject from the local JNI reference \a localRef.
1705 This function takes ownership of \a localRef and frees it before returning.
1706
1707 \note Only call this function with a local JNI reference. For example, most raw JNI calls,
1708 through the JNI environment, return local references to a java object.
1709
1710 \code
1711 jobject localRef = env->GetObjectArrayElement(array, index);
1712 QJniObject element = QJniObject::fromLocalRef(localRef);
1713 \endcode
1714*/
1715QJniObject QJniObject::fromLocalRef(jobject lref)
1716{
1717 QJniObject obj(lref);
1718 obj.jniEnv()->DeleteLocalRef(lref);
1719 return obj;
1720}
1721
1722bool QJniObject::isSameObject(jobject obj) const
1723{
1724 if (!d)
1725 return obj == nullptr;
1726 if (d->m_jobject == obj)
1727 return true;
1728 if (!d->m_jobject || !obj)
1729 return false;
1730 return jniEnv()->IsSameObject(d->m_jobject, obj);
1731}
1732
1733bool QJniObject::isSameObject(const QJniObject &other) const
1734{
1735 if (!other.isValid())
1736 return !isValid();
1737 return isSameObject(other.d->m_jobject);
1738}
1739
1740void QJniObject::assign(jobject obj)
1741{
1742 if (d && isSameObject(obj))
1743 return;
1744
1745 d = QSharedPointer<QJniObjectPrivate>::create();
1746 if (obj) {
1747 JNIEnv *env = jniEnv();
1748 d->m_jobject = env->NewGlobalRef(obj);
1749 jclass objectClass = env->GetObjectClass(obj);
1750 d->m_jclass = static_cast<jclass>(env->NewGlobalRef(objectClass));
1751 env->DeleteLocalRef(objectClass);
1752 }
1753}
1754
1755jobject QJniObject::javaObject() const
1756{
1757 return d->m_jobject;
1758}
1759
1760/*!
1761 \class QtJniTypes::JObjectBase
1762 \brief The JObjectBase in the QtJniTypes namespace is the base of all declared Java types.
1763 \inmodule QtCore
1764 \internal
1765*/
1766
1767/*!
1768 \class QtJniTypes::JObject
1769 \inmodule QtCore
1770 \brief The JObject template in the QtJniTypes namespace is the base of declared Java types.
1771 \since Qt 6.8
1772
1773 JObject<Type> is a template class where \a Type specifies the Java type
1774 being represented.
1775
1776 This template gets specialized when using the Q_DECLARE_JNI_CLASS macro. The
1777 specialization produces a unique type in the QtJniTypes namespace. This
1778 allows the type system to deduce the correct signature in JNI calls when an
1779 instance of the specialized type is passed as a parameter.
1780
1781 Instances can be implicitly converted to and from QJniObject and jobject,
1782 and provide the same template API as QJniObject to call methods and access
1783 properties. Since instances of JObject know about the Java type they hold,
1784 APIs to access static methods or fields do not require the class name as an
1785 explicit parameter.
1786
1787 \sa Q_DECLARE_JNI_CLASS
1788*/
1789
1790/*!
1791 \fn template <typename Type> QtJniTypes::JObject<Type>::JObject()
1792
1793 Default-constructs the JObject instance by calling the no-argument
1794 constructor of the represented Java type.
1795
1796 Not every Java class has a no-argument constructor. For those, use
1797 construct() or the constructor that takes arguments, otherwise the call
1798 fails at runtime. To get a null instance, use \c {JObject(nullptr)}.
1799
1800 \sa construct()
1801*/
1802
1803/*!
1804 \fn template <typename Type> QtJniTypes::JObject<Type>::JObject(const QJniObject &other)
1805
1806 Constructs a JObject instance that holds a reference to the same jobject as \a other.
1807*/
1808
1809/*!
1810 \fn template <typename Type> QtJniTypes::JObject<Type>::JObject(jobject other)
1811
1812 Constructs a JObject instance that holds a reference to \a other.
1813*/
1814
1815/*!
1816 \fn template <typename Type> QtJniTypes::JObject<Type>::JObject(QJniObject &&other)
1817
1818 Move-constructs a JObject instance from \a other.
1819*/
1820
1821/*!
1822 \fn template <typename Type> bool QtJniTypes::JObject<Type>::isValid() const
1823
1824 Returns whether the JObject instance holds a valid reference to a jobject.
1825
1826 \sa QJniObject::isValid()
1827*/
1828
1829/*!
1830 \fn template <typename Type> jclass QtJniTypes::JObject<Type>::objectClass() const
1831
1832 Returns the Java class that this JObject is an instance of as a jclass.
1833
1834 \sa className(), QJniObject::objectClass()
1835*/
1836
1837/*!
1838 \fn template <typename Type> QString QtJniTypes::JObject<Type>::toString() const
1839
1840 Returns a QString with a string representation of the Java object.
1841
1842 \sa QJniObject::toString()
1843*/
1844
1845/*!
1846 \fn template <typename Type> QByteArray QtJniTypes::JObject<Type>::className() const
1847
1848 Returns the name of the Java class that this object is an instance of.
1849
1850 \sa objectClass(), QJniObject::className()
1851*/
1852
1853/*!
1854 \fn template <typename Type> bool QtJniTypes::JObject<Type>::isClassAvailable()
1855
1856 Returns whether the class that this JObject specialization represents is
1857 available.
1858
1859 \sa QJniObject::isClassAvailable()
1860*/
1861
1862/*!
1863 \fn template <typename Type> JObject QtJniTypes::JObject<Type>::fromJObject(jobject object)
1864
1865 Constructs a JObject instance from \a object and returns that instance.
1866*/
1867
1868/*!
1869 \fn template <typename Type> template <typename ...Args> JObject QtJniTypes::JObject<Type>::construct(Args &&...args)
1870
1871 Constructs a Java object from \a args and returns a JObject instance that
1872 holds a reference to that Java object.
1873*/
1874
1875/*!
1876 \fn template <typename Type> JObject QtJniTypes::JObject<Type>::fromLocalRef(jobject ref)
1877
1878 Constructs a JObject that holds a local reference to \a ref, and returns
1879 that object.
1880*/
1881
1882/*!
1883 \fn template <typename Type> template <typename Ret, typename ...Args> auto QtJniTypes::JObject<Type>::callStaticMethod(const char *methodName, Args &&...args)
1884
1885 Calls the static method \a methodName with arguments \a args, and returns
1886 the result of type Ret (unless Ret is \c void). If Ret is a
1887 jobject type, then the returned value will be a QJniObject.
1888
1889 \sa QJniObject::callStaticMethod()
1890*/
1891
1892/*!
1893 \fn template <typename Type> bool QtJniTypes::JObject<Type>::registerNativeMethods(std::initializer_list<JNINativeMethod> methods)
1894
1895 Registers the Java methods in \a methods with the Java class represented by
1896 the JObject specialization, and returns whether the registration was successful.
1897
1898 \sa QJniEnvironment::registerNativeMethods()
1899*/
1900
1901/*!
1902 \fn template <typename Type> template <typename T> auto QtJniTypes::JObject<Type>::getStaticField(const char *field)
1903
1904 Returns the value of the static field \a field.
1905
1906 \sa QJniObject::getStaticField()
1907*/
1908
1909/*!
1910 \fn template <typename Type> template <typename Ret, typename T> auto QtJniTypes::JObject<Type>::setStaticField(const char *field, T &&value)
1911
1912 Sets the static field \a field to \a value.
1913
1914 \sa QJniObject::setStaticField()
1915*/
1916
1917/*!
1918 \fn template <typename Type> template <typename Ret, typename ...Args> auto QtJniTypes::JObject<Type>::callMethod(const char *method, Args &&...args) const
1919
1920 Calls the instance method \a method with arguments \a args, and returns
1921 the result of type Ret (unless Ret is \c void). If Ret is a
1922 jobject type, then the returned value will be a QJniObject.
1923
1924 \sa QJniObject::callMethod()
1925*/
1926
1927/*!
1928 \fn template <typename Type> template <typename T> auto QtJniTypes::JObject<Type>::getField(const char *field) const
1929
1930 Returns the value of the instance field \a field.
1931
1932 \sa QJniObject::getField()
1933*/
1934
1935/*!
1936 \fn template <typename Type> template <typename Ret, typename T> auto QtJniTypes::JObject<Type>::setField(const char *field, T &&value)
1937
1938 Sets the value of the instance field \a field to \a value.
1939
1940 \sa QJniObject::setField()
1941*/
1942
1943
1944QT_END_NAMESPACE
bool isJString(JNIEnv *env) const
IsJString m_is_jstring
QByteArray m_className
void construct(const char *signature=nullptr, Args &&...args)
Combined button and popup list for selecting options.
static QByteArray cacheKey(Args &&...args)
static void throwInstantiationException(JNIEnv *env, QByteArray className, jclass clazz)
static bool isClassInstantiable(JNIEnv *env, const QByteArray &className, jclass clazz)
jmethodID loadClassMethod
jclass clazz
Instantiable instantiable