xref: /aosp_15_r20/external/webrtc/sdk/android/src/jni/scoped_java_ref_counted.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2019 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 #ifndef SDK_ANDROID_SRC_JNI_SCOPED_JAVA_REF_COUNTED_H_
11 #define SDK_ANDROID_SRC_JNI_SCOPED_JAVA_REF_COUNTED_H_
12 
13 #include "sdk/android/native_api/jni/scoped_java_ref.h"
14 
15 namespace webrtc {
16 namespace jni {
17 
18 // Holds a reference to a java object implementing the RefCounted interface, and
19 // calls its release() method from the destructor.
20 class ScopedJavaRefCounted {
21  public:
22   // Takes over the caller's reference.
Adopt(JNIEnv * jni,const JavaRef<jobject> & j_object)23   static ScopedJavaRefCounted Adopt(JNIEnv* jni,
24                                     const JavaRef<jobject>& j_object) {
25     return ScopedJavaRefCounted(jni, j_object);
26   }
27 
28   // Retains the java object for the live time of this object.
29   static ScopedJavaRefCounted Retain(JNIEnv* jni,
30                                      const JavaRef<jobject>& j_object);
31   ScopedJavaRefCounted(ScopedJavaRefCounted&& other) = default;
32 
33   ScopedJavaRefCounted(const ScopedJavaRefCounted& other) = delete;
34   ScopedJavaRefCounted& operator=(const ScopedJavaRefCounted&) = delete;
35 
36   ~ScopedJavaRefCounted();
37 
38  private:
39   // Adopts reference.
ScopedJavaRefCounted(JNIEnv * jni,const JavaRef<jobject> & j_object)40   ScopedJavaRefCounted(JNIEnv* jni, const JavaRef<jobject>& j_object)
41       : j_object_(jni, j_object) {}
42 
43   ScopedJavaGlobalRef<jobject> j_object_;
44 };
45 
46 }  // namespace jni
47 }  // namespace webrtc
48 
49 #endif  // SDK_ANDROID_SRC_JNI_SCOPED_JAVA_REF_COUNTED_H_
50