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_GLOBAL_REFERENCE_H_ | |
6 #define BASE_ANDROID_SCOPED_JAVA_GLOBAL_REFERENCE_H_ | |
7 | |
8 #include <jni.h> | |
9 #include <stddef.h> | |
10 | |
11 #include "base/android/scoped_java_reference.h" | |
12 #include "base/basictypes.h" | |
13 | |
14 namespace base { | |
15 namespace android { | |
16 | |
17 // Holds a global reference to a Java object. The global reference is scoped | |
18 // to the lifetime of this object. Note that since a JNI Env is only suitable | |
19 // for use on a single thread, objects of this class must be created, used and | |
20 // destroyed on the same thread. | |
21 template<typename T> | |
22 class ScopedJavaGlobalReference { | |
23 public: | |
24 // Holds a NULL reference. | |
25 ScopedJavaGlobalReference() | |
26 : env_(NULL), | |
27 obj_(NULL) { | |
28 } | |
29 // Takes a new global reference to the Java object held by obj. | |
30 explicit ScopedJavaGlobalReference(const ScopedJavaReference<T>& obj) | |
31 : env_(obj.env()), | |
32 obj_(static_cast<T>(obj.env()->NewGlobalRef(obj.obj()))) { | |
33 } | |
34 ~ScopedJavaGlobalReference() { | |
35 Reset(); | |
36 } | |
37 | |
38 void Reset() { | |
39 if (env_ && obj_) | |
40 env_->DeleteGlobalRef(obj_); | |
41 env_ = NULL; | |
42 obj_ = NULL; | |
43 } | |
44 void Reset(const ScopedJavaGlobalReference& other) { | |
45 Reset(); | |
46 env_ = other.env_; | |
47 obj_ = other.env_ ? static_cast<T>(other.env_->NewGlobalRef(other.obj_)) : | |
48 NULL; | |
49 } | |
50 | |
51 T obj() const { return obj_; } | |
52 | |
53 private: | |
54 JNIEnv* env_; | |
55 T obj_; | |
56 | |
57 DISALLOW_COPY_AND_ASSIGN(ScopedJavaGlobalReference); | |
58 }; | |
59 | |
60 } // namespace android | |
61 } // namespace base | |
62 | |
63 #endif // BASE_ANDROID_SCOPED_JAVA_GLOBAL_REFERENCE_H_ | |
OLD | NEW |