Home | History | Annotate | Download | only in include
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      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
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     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.
     23 template<typename T>
     24 class ScopedLocalRef {
     25 public:
     26     ScopedLocalRef(JNIEnv* env, T localRef)
     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 
     42     T get() const {
     43         return mLocalRef;
     44     }
     45 
     46 private:
     47     JNIEnv* mEnv;
     48     T mLocalRef;
     49 
     50     // Disallow copy and assignment.
     51     ScopedLocalRef(const ScopedLocalRef&);
     52     void operator=(const ScopedLocalRef&);
     53 };
     54 
     55 #endif  // SCOPED_LOCAL_REF_H_included
     56