Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2010 The Android Open Source Project |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 3 | * |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 7 | * |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 9 | * |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef SCOPED_LOCAL_REF_H_included |
| 18 | #define SCOPED_LOCAL_REF_H_included |
| 19 | |
| 20 | #include "JNIHelp.h" |
| 21 | |
| 22 | // A smart pointer that deletes a JNI local reference when it goes out of scope. |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 23 | template<typename T> |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 24 | class ScopedLocalRef { |
| 25 | public: |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 26 | ScopedLocalRef(JNIEnv* env, T localRef) |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 27 | : mEnv(env), mLocalRef(localRef) |
| 28 | { |
| 29 | } |
| 30 | |
| 31 | ~ScopedLocalRef() { |
| 32 | reset(); |
| 33 | } |
| 34 | |
| 35 | void reset() { |
| 36 | if (mLocalRef != NULL) { |
| 37 | mEnv->DeleteLocalRef(mLocalRef); |
| 38 | mLocalRef = NULL; |
| 39 | } |
| 40 | } |
| 41 | |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 42 | T get() const { |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 43 | return mLocalRef; |
| 44 | } |
| 45 | |
| 46 | private: |
| 47 | JNIEnv* mEnv; |
Elliott Hughes | 8044bf6 | 2010-05-17 22:34:46 -0700 | [diff] [blame] | 48 | T mLocalRef; |
Elliott Hughes | f281667 | 2010-05-11 17:16:02 -0700 | [diff] [blame] | 49 | |
| 50 | // Disallow copy and assignment. |
| 51 | ScopedLocalRef(const ScopedLocalRef&); |
| 52 | void operator=(const ScopedLocalRef&); |
| 53 | }; |
| 54 | |
| 55 | #endif // SCOPED_LOCAL_REF_H_included |