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