Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: jni/Utils.h

Issue 4761138508070912: Issue 1848 - Clean up local reference handling (Closed)
Patch Set: Removed member variable prefixes Created Jan. 23, 2015, 1:16 p.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: jni/Utils.h
diff --git a/jni/Utils.h b/jni/Utils.h
index 852457cdd95095e57e8232fe2b40ae316814c636..17d5085510c82c1965897eae0c814bf1c62b55b9 100644
--- a/jni/Utils.h
+++ b/jni/Utils.h
@@ -39,6 +39,43 @@ void JniThrowException(JNIEnv* env, const std::exception& e);
void JniThrowException(JNIEnv* env);
+class JNIEnvAcquire;
+
+/**
+ * This class is _NOT_ thread safe!
+ */
+template<typename T>
+class JniLocalReference
+{
+public:
+ explicit JniLocalReference(JNIEnv* jniEnv, T object)
Felix Dahlke 2015/02/03 05:22:50 Doesn't need to be explicit since there's two argu
René Jeschke 2015/02/03 13:51:26 Done.
+ : jniEnv(jniEnv), object(object)
+ {
+
+ }
+
+ JniLocalReference(const JniLocalReference<T>& other);
+
+ ~JniLocalReference()
+ {
+ jniEnv->DeleteLocalRef(object);
+ }
+
+ T operator*()
+ {
+ return object;
+ }
+
+ T Get()
+ {
+ return object;
+ }
+
+private:
+ JNIEnv* jniEnv;
+ T object;
+};
+
class JNIEnvAcquire
{
public:
@@ -145,21 +182,24 @@ inline jobject NewJniFilter(JNIEnv* env, const AdblockPlus::FilterPtr& filter)
return 0;
}
- jclass clazz = env->FindClass(PKG("Filter"));
- jmethodID method = env->GetMethodID(clazz, "<init>", "(J)V");
- return env->NewObject(clazz, method, JniPtrToLong(new AdblockPlus::FilterPtr(filter)));
+ JniLocalReference<jclass> clazz(env, env->FindClass(PKG("Filter")));
+ jmethodID method = env->GetMethodID(*clazz, "<init>", "(J)V");
+ return env->NewObject(*clazz, method,
+ JniPtrToLong(new AdblockPlus::FilterPtr(filter)));
}
-inline jobject NewJniSubscription(JNIEnv* env, const AdblockPlus::SubscriptionPtr& subscription)
+inline jobject NewJniSubscription(JNIEnv* env,
+ const AdblockPlus::SubscriptionPtr& subscription)
{
if (!subscription.get())
{
return 0;
}
- jclass clazz = env->FindClass(PKG("Subscription"));
- jmethodID method = env->GetMethodID(clazz, "<init>", "(J)V");
- return env->NewObject(clazz, method, JniPtrToLong(new AdblockPlus::SubscriptionPtr(subscription)));
+ JniLocalReference<jclass> clazz(env, env->FindClass(PKG("Subscription")));
+ jmethodID method = env->GetMethodID(*clazz, "<init>", "(J)V");
+ return env->NewObject(*clazz, method,
+ JniPtrToLong(new AdblockPlus::SubscriptionPtr(subscription)));
}
#define CATCH_AND_THROW(jEnv) \

Powered by Google App Engine
This is Rietveld