Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / service / resource-encapsulation / android / service / src / main / jni / util / JavaLocalRef.h
1 /******************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 #ifndef JAVA_LOCAL_REF_H_
22 #define JAVA_LOCAL_REF_H_
23
24 #include <jni.h>
25 #include <cassert>
26
27 template < typename T >
28 class JavaLocalRef
29 {
30 public:
31     JavaLocalRef(JNIEnv* env, T obj) noexcept :
32         m_env{ env },
33         m_obj{ obj }
34     {
35         assert(env && "JNIEnv is nullptr");
36     }
37
38     template< typename ENV >
39     JavaLocalRef(ENV* env, T obj) noexcept :
40         m_env{ env->get() },
41         m_obj{ obj }
42     {
43         assert(env && "JNIEnv is nullptr");
44     }
45
46     ~JavaLocalRef()
47     {
48         if (m_obj) m_env->DeleteLocalRef(m_obj);
49     }
50
51     operator bool() const noexcept { return m_obj; }
52     operator T() const noexcept { return m_obj; }
53
54     jobject get() const noexcept { return m_obj; }
55
56     JavaLocalRef(const JavaLocalRef&) = delete;
57     JavaLocalRef& operator=(const JavaLocalRef&) = delete;
58
59     JavaLocalRef& operator=(JavaLocalRef&&) = delete;
60
61 private:
62     JNIEnv* m_env;
63     T m_obj;
64 };
65
66 typedef JavaLocalRef< jobject > JavaLocalObject;
67 typedef JavaLocalRef< jstring > JavaLocalString;
68 typedef JavaLocalRef< jclass > JavaLocalClass;
69
70 #endif // JAVA_LOCAL_REF_H_