Paulo Marcio
Paulo Marcio

Reputation: 245

Android Class.forName can't load class with default class loader

I'm developing an android game with LibGDX and there is a lot of classes loaded dynamically, in the release version of the apk i can't load them using:

Class.forName(className);

I get ClassNotFoundException, analyzing the apk i saw that the classes name inside the dex file get simplified to one letter only, i guess thats why i cant load. LibGDX project has two parts: core and android, the first does the loading that i want and have no android API deps, he is indeed a dep to the android project who will run inside an activity and use functionalities from the core.

On the android project i can load the classes using this example code inse the onCreate:

    try {
        Class clazz = Class.forName("game.ui.TreasureChest");
        TreasureChest chest = (TreasureChest)clazz.newInstance();
        chest.update(0.0f);
    }catch(Exception ex){
        Log.v("loadClassses", "exception: " + ex.getMessage());
    }

This code gives me no exception, apparently the two projects uses differents class loaders and the android version is specialized for this dex files. This code won't work:

        Class clazz = Class.forName("game.ui.TreasureChest", true, this.getClass().getClassLoader());

Why is this happening? In the android docs it is said that the first example is equivalent to the second, so there shouldn't be an exception.

There is another solution for me to load these classes? I was thinking in an interface, where the android project would implement to load a given class by the name, but neither variations of the forName method works in the interface.

Upvotes: 0

Views: 535

Answers (1)

Paulo Marcio
Paulo Marcio

Reputation: 245

I found the source of the problem, some time later i was looking at the gradle build files and saw this line:

minifyEabled true

I have put that there a long time ago and it was the cause of the minifed names, then the classloaders couldn't find the classes, removing it made everything work

Upvotes: 1

Related Questions