Home | History | Annotate | Download | only in android
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef BASE_ANDROID_SCOPED_JAVA_REF_H_
      6 #define BASE_ANDROID_SCOPED_JAVA_REF_H_
      7 
      8 #include <jni.h>
      9 #include <stddef.h>
     10 
     11 #include <type_traits>
     12 
     13 #include "base/base_export.h"
     14 #include "base/logging.h"
     15 #include "base/macros.h"
     16 
     17 namespace base {
     18 namespace android {
     19 
     20 // Creates a new local reference frame, in which at least a given number of
     21 // local references can be created. Note that local references already created
     22 // in previous local frames are still valid in the current local frame.
     23 class BASE_EXPORT ScopedJavaLocalFrame {
     24  public:
     25   explicit ScopedJavaLocalFrame(JNIEnv* env);
     26   ScopedJavaLocalFrame(JNIEnv* env, int capacity);
     27   ~ScopedJavaLocalFrame();
     28 
     29  private:
     30   // This class is only good for use on the thread it was created on so
     31   // it's safe to cache the non-threadsafe JNIEnv* inside this object.
     32   JNIEnv* env_;
     33 
     34   DISALLOW_COPY_AND_ASSIGN(ScopedJavaLocalFrame);
     35 };
     36 
     37 // Forward declare the generic java reference template class.
     38 template<typename T> class JavaRef;
     39 
     40 // Template specialization of JavaRef, which acts as the base class for all
     41 // other JavaRef<> template types. This allows you to e.g. pass
     42 // ScopedJavaLocalRef<jstring> into a function taking const JavaRef<jobject>&
     43 template<>
     44 class BASE_EXPORT JavaRef<jobject> {
     45  public:
     46   // Allow nullptr to be converted to JavaRef. This avoids having to declare an
     47   // empty ScopedJavaLocalRef just to pass null to a function with a JavaRef
     48   // parameter, and makes C++ "nullptr" and Java "null" equivalent.
     49   JavaRef(std::nullptr_t) : JavaRef() {}
     50 
     51   // Public to allow destruction of temporary JavaRef objects created by the
     52   // nullptr conversion. Don't add anything else here; it's inlined.
     53   ~JavaRef() {}
     54 
     55   jobject obj() const { return obj_; }
     56 
     57   bool is_null() const { return obj_ == NULL; }
     58 
     59  protected:
     60   // Initializes a NULL reference. Don't add anything else here; it's inlined.
     61   JavaRef() : obj_(NULL) {}
     62 
     63   // Takes ownership of the |obj| reference passed; requires it to be a local
     64   // reference type.
     65 #if DCHECK_IS_ON()
     66   // Implementation contains a DCHECK; implement out-of-line when DCHECK_IS_ON.
     67   JavaRef(JNIEnv* env, jobject obj);
     68 #else
     69   // Don't add anything else here; it's inlined.
     70   JavaRef(JNIEnv* env, jobject obj) : obj_(obj) {}
     71 #endif
     72 
     73   // The following are implementation detail convenience methods, for
     74   // use by the sub-classes.
     75   JNIEnv* SetNewLocalRef(JNIEnv* env, jobject obj);
     76   void SetNewGlobalRef(JNIEnv* env, jobject obj);
     77   void ResetLocalRef(JNIEnv* env);
     78   void ResetGlobalRef();
     79   jobject ReleaseInternal();
     80 
     81  private:
     82   jobject obj_;
     83 
     84   DISALLOW_COPY_AND_ASSIGN(JavaRef);
     85 };
     86 
     87 // Generic base class for ScopedJavaLocalRef and ScopedJavaGlobalRef. Useful
     88 // for allowing functions to accept a reference without having to mandate
     89 // whether it is a local or global type.
     90 template<typename T>
     91 class JavaRef : public JavaRef<jobject> {
     92  public:
     93   JavaRef(std::nullptr_t) : JavaRef<jobject>(nullptr) {}
     94   ~JavaRef() {}
     95 
     96   T obj() const { return static_cast<T>(JavaRef<jobject>::obj()); }
     97 
     98  protected:
     99   JavaRef() {}
    100 
    101   JavaRef(JNIEnv* env, T obj) : JavaRef<jobject>(env, obj) {}
    102 
    103  private:
    104   DISALLOW_COPY_AND_ASSIGN(JavaRef);
    105 };
    106 
    107 // Holds a local reference to a JNI method parameter.
    108 // Method parameters should not be deleted, and so this class exists purely to
    109 // wrap them as a JavaRef<T> in the JNI binding generator. Do not create
    110 // instances manually.
    111 template<typename T>
    112 class JavaParamRef : public JavaRef<T> {
    113  public:
    114   // Assumes that |obj| is a parameter passed to a JNI method from Java.
    115   // Does not assume ownership as parameters should not be deleted.
    116   JavaParamRef(JNIEnv* env, T obj) : JavaRef<T>(env, obj) {}
    117 
    118   // Allow nullptr to be converted to JavaParamRef. Some unit tests call JNI
    119   // methods directly from C++ and pass null for objects which are not actually
    120   // used by the implementation (e.g. the caller object); allow this to keep
    121   // working.
    122   JavaParamRef(std::nullptr_t) : JavaRef<T>(nullptr) {}
    123 
    124   ~JavaParamRef() {}
    125 
    126   // TODO(torne): remove this cast once we're using JavaRef consistently.
    127   // http://crbug.com/506850
    128   operator T() const { return JavaRef<T>::obj(); }
    129 
    130  private:
    131   DISALLOW_COPY_AND_ASSIGN(JavaParamRef);
    132 };
    133 
    134 // Holds a local reference to a Java object. The local reference is scoped
    135 // to the lifetime of this object.
    136 // Instances of this class may hold onto any JNIEnv passed into it until
    137 // destroyed. Therefore, since a JNIEnv is only suitable for use on a single
    138 // thread, objects of this class must be created, used, and destroyed, on a
    139 // single thread.
    140 // Therefore, this class should only be used as a stack-based object and from a
    141 // single thread. If you wish to have the reference outlive the current
    142 // callstack (e.g. as a class member) or you wish to pass it across threads,
    143 // use a ScopedJavaGlobalRef instead.
    144 template<typename T>
    145 class ScopedJavaLocalRef : public JavaRef<T> {
    146  public:
    147   ScopedJavaLocalRef() : env_(NULL) {}
    148 
    149   // Non-explicit copy constructor, to allow ScopedJavaLocalRef to be returned
    150   // by value as this is the normal usage pattern.
    151   ScopedJavaLocalRef(const ScopedJavaLocalRef<T>& other)
    152       : env_(other.env_) {
    153     this->SetNewLocalRef(env_, other.obj());
    154   }
    155 
    156   template<typename U>
    157   explicit ScopedJavaLocalRef(const U& other)
    158       : env_(NULL) {
    159     this->Reset(other);
    160   }
    161 
    162   // Assumes that |obj| is a local reference to a Java object and takes
    163   // ownership  of this local reference.
    164   ScopedJavaLocalRef(JNIEnv* env, T obj) : JavaRef<T>(env, obj), env_(env) {}
    165 
    166   ~ScopedJavaLocalRef() {
    167     this->Reset();
    168   }
    169 
    170   // Overloaded assignment operator defined for consistency with the implicit
    171   // copy constructor.
    172   void operator=(const ScopedJavaLocalRef<T>& other) {
    173     this->Reset(other);
    174   }
    175 
    176   void Reset() {
    177     this->ResetLocalRef(env_);
    178   }
    179 
    180   template<typename U>
    181   void Reset(const ScopedJavaLocalRef<U>& other) {
    182     // We can copy over env_ here as |other| instance must be from the same
    183     // thread as |this| local ref. (See class comment for multi-threading
    184     // limitations, and alternatives).
    185     this->Reset(other.env_, other.obj());
    186   }
    187 
    188   template<typename U>
    189   void Reset(const U& other) {
    190     // If |env_| was not yet set (is still NULL) it will be attached to the
    191     // current thread in SetNewLocalRef().
    192     this->Reset(env_, other.obj());
    193   }
    194 
    195   template<typename U>
    196   void Reset(JNIEnv* env, U obj) {
    197     static_assert(std::is_convertible<U, T>::value,
    198                   "U must be convertible to T");
    199     env_ = this->SetNewLocalRef(env, obj);
    200   }
    201 
    202   // Releases the local reference to the caller. The caller *must* delete the
    203   // local reference when it is done with it. Note that calling a Java method
    204   // is *not* a transfer of ownership and Release() should not be used.
    205   T Release() {
    206     return static_cast<T>(this->ReleaseInternal());
    207   }
    208 
    209  private:
    210   // This class is only good for use on the thread it was created on so
    211   // it's safe to cache the non-threadsafe JNIEnv* inside this object.
    212   JNIEnv* env_;
    213 
    214   // Prevent ScopedJavaLocalRef(JNIEnv*, T obj) from being used to take
    215   // ownership of a JavaParamRef's underlying object - parameters are not
    216   // allowed to be deleted and so should not be owned by ScopedJavaLocalRef.
    217   // TODO(torne): this can be removed once JavaParamRef no longer has an
    218   // implicit conversion back to T.
    219   ScopedJavaLocalRef(JNIEnv* env, const JavaParamRef<T>& other);
    220 };
    221 
    222 // Holds a global reference to a Java object. The global reference is scoped
    223 // to the lifetime of this object. This class does not hold onto any JNIEnv*
    224 // passed to it, hence it is safe to use across threads (within the constraints
    225 // imposed by the underlying Java object that it references).
    226 template<typename T>
    227 class ScopedJavaGlobalRef : public JavaRef<T> {
    228  public:
    229   ScopedJavaGlobalRef() {}
    230 
    231   ScopedJavaGlobalRef(const ScopedJavaGlobalRef<T>& other) {
    232     this->Reset(other);
    233   }
    234 
    235   ScopedJavaGlobalRef(JNIEnv* env, T obj) { this->Reset(env, obj); }
    236 
    237   template<typename U>
    238   explicit ScopedJavaGlobalRef(const U& other) {
    239     this->Reset(other);
    240   }
    241 
    242   ~ScopedJavaGlobalRef() {
    243     this->Reset();
    244   }
    245 
    246   // Overloaded assignment operator defined for consistency with the implicit
    247   // copy constructor.
    248   void operator=(const ScopedJavaGlobalRef<T>& other) {
    249     this->Reset(other);
    250   }
    251 
    252   void Reset() {
    253     this->ResetGlobalRef();
    254   }
    255 
    256   template<typename U>
    257   void Reset(const U& other) {
    258     this->Reset(NULL, other.obj());
    259   }
    260 
    261   template<typename U>
    262   void Reset(JNIEnv* env, const JavaParamRef<U>& other) {
    263     this->Reset(env, other.obj());
    264   }
    265 
    266   template<typename U>
    267   void Reset(JNIEnv* env, U obj) {
    268     static_assert(std::is_convertible<U, T>::value,
    269                   "U must be convertible to T");
    270     this->SetNewGlobalRef(env, obj);
    271   }
    272 
    273   // Releases the global reference to the caller. The caller *must* delete the
    274   // global reference when it is done with it. Note that calling a Java method
    275   // is *not* a transfer of ownership and Release() should not be used.
    276   T Release() {
    277     return static_cast<T>(this->ReleaseInternal());
    278   }
    279 };
    280 
    281 }  // namespace android
    282 }  // namespace base
    283 
    284 #endif  // BASE_ANDROID_SCOPED_JAVA_REF_H_
    285