当需要动态加载某一个类的实现,而这个类又实现了某个接口
可以这样:(这个需要实例化的类有默认的构造函数)
TestInterface curInstance = null;
try
{
curInstance = (TestInterface) Class.forName(className).newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
return curInstance;
但是,当需要实例化的类没有默认的构造器,有含参的构造器,就无法直接调用无参的newInstance(),例如:
public class Test {
public static void main(String[] args) {
Class<Integer> c = Integer.class;
try {
int var = c.getConstructor(int.class).newInstance(111);
System.out.println(var);
} catch(Exception e) {
e.printStackTrace();
}
}
}
DexClassLoader dexLoader = getDexClassLoader(this.m_context, _dexPath);
Class localClass = dexLoader.loadClass(classname);
Constructor localConstructor = localClass.getConstructor(new Class[] {Context.class});
IPlugin localPlugin = (IPlugin) localConstructor.newInstance(new Object[] {m_context});//实例化插件