OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2011 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_REFERENCE_H_ |
| 6 #define BASE_ANDROID_SCOPED_JAVA_REFERENCE_H_ |
| 7 |
| 8 #include <jni.h> |
| 9 #include <stddef.h> |
| 10 |
| 11 namespace base { |
| 12 namespace android { |
| 13 |
| 14 // Holds a local reference to a Java object. The local reference is scoped |
| 15 // to the lifetime of this object. Note that since a JNI Env is only suitable |
| 16 // for use on a single thread, objects of this class must be created, used and |
| 17 // destroyed on the same thread. |
| 18 template<typename T> |
| 19 class ScopedJavaReference { |
| 20 public: |
| 21 // Holds a NULL reference. |
| 22 ScopedJavaReference() |
| 23 : env_(NULL), |
| 24 obj_(NULL) { |
| 25 } |
| 26 // Assumes that obj is a local reference to a Java object and takes ownership |
| 27 // of this local reference. |
| 28 ScopedJavaReference(JNIEnv* env, T obj) |
| 29 : env_(env), |
| 30 obj_(obj) { |
| 31 } |
| 32 // Takes a new local reference to the Java object held by other. |
| 33 ScopedJavaReference(const ScopedJavaReference& other) |
| 34 : env_(other.env_), |
| 35 obj_(other.obj_ ? static_cast<T>(other.env_->NewLocalRef(other.obj_)) : |
| 36 NULL) { |
| 37 } |
| 38 ~ScopedJavaReference() { |
| 39 if (obj_) |
| 40 env_->DeleteLocalRef(obj_); |
| 41 } |
| 42 |
| 43 void operator=(const ScopedJavaReference& other) { |
| 44 if (obj_) |
| 45 env_->DeleteLocalRef(obj_); |
| 46 env_ = other.env_; |
| 47 obj_ = other.obj_ ? static_cast<T>(env_->NewLocalRef(other.obj_)) : NULL; |
| 48 } |
| 49 |
| 50 JNIEnv* env() const { return env_; } |
| 51 T obj() const { return obj_; } |
| 52 |
| 53 // Releases the local reference to the caller. The caller *must* delete the |
| 54 // local reference when it is done with it. |
| 55 T Release() { |
| 56 jobject obj = obj_; |
| 57 obj_ = NULL; |
| 58 return obj; |
| 59 } |
| 60 |
| 61 private: |
| 62 JNIEnv* env_; |
| 63 T obj_; |
| 64 }; |
| 65 |
| 66 } // namespace android |
| 67 } // namespace base |
| 68 |
| 69 #endif // BASE_ANDROID_SCOPED_JAVA_REFERENCE_H_ |
OLD | NEW |