lundi 13 avril 2015

Android ClassLoader: loadClass fails if class implements and interface

I'm using the following code to dynamically load a class from an external package:



Object plugin = null;
String packageName = "unipd.elia.deltapluginaccelerometersensor";
String className = "unipd.elia.deltapluginaccelerometersensor.AccelerometerPlugin";
try {
PackageManager packageManager = getPackageManager();
ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName, 0);
DexFile df = new DexFile(appInfo.sourceDir);
ClassLoader cl = getClassLoader();
Class classToInvestigate = df.loadClass(className, cl);
plugin = classToInvestigate.newInstance();


} catch (Exception e) {
System.out.println("EXCEPTION");
}


The problem is the following: if the class I try to load is a "simple" class everything goes fine, but if it implents an interface the loading fails. Here's an example of a class that fails to load:



package unipd.elia.deltapluginaccelerometersensor;

public class AccelerometerPlugin implements IDeltaPlugin {

@Override
public String getPluginName() {
return "Accelerometer Sensor Plugin";
}

@Override
public String getPluginID() {
return "delta.plugin.accelerometersensor";
}

@Override
public String getPluginAuthor() {
return "Me";
}
}


And the interface it implements:



public interface IDeltaPlugin {

String getPluginName();
String getPluginID();
String getPluginAuthor();
}


Basically the call to loadClass() returns null if the class implements the interface. Remove the "implements" statement and it loads fine.


What am I doing wrong?






Aucun commentaire:

Enregistrer un commentaire