1 /** 2 * @copyright 3 * ==================================================================== 4 * Licensed to the Apache Software Foundation (ASF) under one 5 * or more contributor license agreements. See the NOTICE file 6 * distributed with this work for additional information 7 * regarding copyright ownership. The ASF licenses this file 8 * to you under the Apache License, Version 2.0 (the 9 * "License"); you may not use this file except in compliance 10 * with the License. You may obtain a copy of the License at 11 * 12 * http://www.apache.org/licenses/LICENSE-2.0 13 * 14 * Unless required by applicable law or agreed to in writing, 15 * software distributed under the License is distributed on an 16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 * KIND, either express or implied. See the License for the 18 * specific language governing permissions and limitations 19 * under the License. 20 * ==================================================================== 21 * @endcopyright 22 */ 23 24 #ifndef SVN_JAVAHL_JNIWRAPPER_GLOBALREF_HPP 25 #define SVN_JAVAHL_JNIWRAPPER_GLOBALREF_HPP 26 27 #include <memory> 28 29 #include <jni.h> 30 31 #include "jni_env.hpp" 32 33 namespace Java { 34 35 /** 36 * Wrapper for a global object reference. The reference is held until 37 * the wrapper goes out of scope (i.e., until the destructor is called). 38 * 39 * @since New in 1.9. 40 */ 41 class GlobalObject 42 { 43 public: GlobalObject(Env env,jobject obj)44 explicit GlobalObject(Env env, jobject obj) 45 : m_obj(obj ? env.NewGlobalRef(obj) : NULL) 46 {} 47 ~GlobalObject()48 ~GlobalObject() throw() 49 { 50 if (m_obj) 51 Env().DeleteGlobalRef(m_obj); 52 } 53 operator =(jobject that)54 GlobalObject& operator=(jobject that) 55 { 56 this->~GlobalObject(); 57 return *new(this) GlobalObject(Env(), that); 58 } 59 get() const60 jobject get() const throw() 61 { 62 return m_obj; 63 } 64 65 private: 66 GlobalObject(const GlobalObject&); 67 GlobalObject& operator=(const GlobalObject&); 68 69 jobject m_obj; 70 }; 71 72 /** 73 * Wrapper for a global class reference. Behaves just like the object 74 * reference wrapper, but provides a more type-safe interface for 75 * class references. 76 * 77 * @since New in 1.9. 78 */ 79 class GlobalClass : protected GlobalObject 80 { 81 public: GlobalClass(Env env,jclass cls)82 explicit GlobalClass(Env env, jclass cls) 83 : GlobalObject(env, cls) 84 {} 85 operator =(jclass that)86 GlobalClass& operator=(jclass that) 87 { 88 GlobalObject::operator=(that); 89 return *this; 90 } 91 get() const92 jclass get() const throw() 93 { 94 return jclass(GlobalObject::get()); 95 } 96 97 private: 98 GlobalClass(const GlobalClass&); 99 GlobalClass& operator=(const GlobalClass&); 100 }; 101 102 } // namespace Java 103 104 #endif // SVN_JAVAHL_JNIWRAPPER_GLOBALREF_HPP 105