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. | |
16 template<typename T> | |
17 class ScopedJavaReference { | |
18 public: | |
19 // Holds a NULL reference. | |
20 ScopedJavaReference() | |
21 : env_(NULL), | |
22 obj_(NULL) { | |
23 } | |
24 // Assumes that obj is a local reference to a Java object and takes ownership | |
25 // of this local reference. The local reference is deleted when this object | |
26 // goes out of scope. | |
bulach
2011/08/05 12:03:02
same here.
steveblock
2011/08/08 11:28:32
Done.
| |
27 ScopedJavaReference(JNIEnv* env, T obj) | |
28 : env_(env), | |
29 obj_(obj) { | |
30 } | |
31 // Takes a new local reference to the Java object held by other. The local | |
32 // reference is deleted when this object goes out of scope. | |
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_; } | |
bulach
2011/08/05 12:03:02
\n
steveblock
2011/08/08 11:28:32
Done.
| |
52 // Releases the local reference to the caller. The caller *must* delete the | |
53 // local reference when it is done with it. | |
54 T Release() { | |
55 jobject obj = obj_; | |
56 obj_ = NULL; | |
57 return obj; | |
58 } | |
59 | |
60 private: | |
61 | |
bulach
2011/08/05 12:03:02
remove \n
steveblock
2011/08/08 11:28:32
Done.
| |
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 |