blob: 84ee11a956764128cb935862218adb740364c86d [file] [log] [blame]
Elliott Hughesf2816672010-05-11 17:16:02 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
Elliott Hughes8044bf62010-05-17 22:34:46 -07003 *
Elliott Hughesf2816672010-05-11 17:16:02 -07004 * 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 Hughes8044bf62010-05-17 22:34:46 -07007 *
Elliott Hughesf2816672010-05-11 17:16:02 -07008 * http://www.apache.org/licenses/LICENSE-2.0
Elliott Hughes8044bf62010-05-17 22:34:46 -07009 *
Elliott Hughesf2816672010-05-11 17:16:02 -070010 * 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 Hughes8044bf62010-05-17 22:34:46 -070023template<typename T>
Elliott Hughesf2816672010-05-11 17:16:02 -070024class ScopedLocalRef {
25public:
Elliott Hughes8044bf62010-05-17 22:34:46 -070026 ScopedLocalRef(JNIEnv* env, T localRef)
Elliott Hughesf2816672010-05-11 17:16:02 -070027 : 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 Hughes8044bf62010-05-17 22:34:46 -070042 T get() const {
Elliott Hughesf2816672010-05-11 17:16:02 -070043 return mLocalRef;
44 }
45
46private:
47 JNIEnv* mEnv;
Elliott Hughes8044bf62010-05-17 22:34:46 -070048 T mLocalRef;
Elliott Hughesf2816672010-05-11 17:16:02 -070049
50 // Disallow copy and assignment.
51 ScopedLocalRef(const ScopedLocalRef&);
52 void operator=(const ScopedLocalRef&);
53};
54
55#endif // SCOPED_LOCAL_REF_H_included