简体   繁体   中英

FindClass on a Class that was loaded from a jar file at runtime

I am currently head-butting my desk after working on this problem for a couple of days.

My native android app loads a class at runtime, this works I have followed this tutorial to get the dexed jar from the assets folder and have loaded the class and called it's static methods successfully.

However if I run a...

env->FindClass("TheClass"); 

... It throws a java exception.

Here the the relevant bit of the code

//this works find and gives me a usable class
jclass shim_class = helper.LoadClassFromAssetsJar("test.jar","TheClass");
// this throws the exception    
jclass refound_shim_class = jni->FindClass("TheClass"); 

Any help would be incredible, cheers folks

Well there was a real range of things in here.

First as @Alex Cohn said we need to keep the class which is easily done using 'global references' which will make a jobject (or jclass etc) not be reassigned until it is released. I am considering this effect to be thread local as this is what is was in some of the earlier versions of android (as far as I could see)

Next, for reasons I won't bore you with here, we are using the DexClassloader as we are loading our apk fro nthe assets folder (see here for how that works) so we also need to keep hold of this. FindClass will only work in it's own context, which is for loading system classes (though you can load your own if you do this) .

Now we need to be able to use the class from the apk in each thread so we run the declassloader.loadclass when we create the JniEnv for each thread an cache it using a pthread_key . This way we get the class everywhere and deallocation happens automatically via the keythread callbacks.

Anyway that's enough of that. Good Luck!

ps A side note, once a jni method has thrown a unhanded exception you have no guarantee that any other call will work...some will, some won't, some will cause a segfault...So catch liberally from the java side and protect the native side from the java nastiness!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM