Android的Java的无法加载类 [英] Android java unable to load class
问题描述
喜,我无法在我的Android应用程序加载的类,我可以加载基本类,但是当我在这个类初始化上下文然后我不能加载它
hi am unable to load class in my android app , i can load basic class but when i Initialize context in that class then am not able to load it
public class main {
// Initalize context
Context mContext;
public main(Context mContext){
this.mContext = mContext;
}
public boolean main() {
Log.d("MYLOG", "main() called successfully when there context is not initialized like above");
// some code here
}
}
我的类加载code
my class loading code
try{
final File tmpDir = context.getDir("dex", 0);
final DexClassLoader classloader = new DexClassLoader(libPath, tmpDir.getAbsolutePath(), null, this.getClass().getClassLoader());
final Class<Object> classToLoad = (Class<Object>) classloader.loadClass("com.myproject.test.dumy_class"); // package plus main class
final Object myInstance = classToLoad.newInstance(); // throwing exception here
}
} catch (Exception e) {
// exception thrown at that statement : final Object myInstance = classToLoad.newInstance();
}
例外,我得到了:
Exception i got :
java.lang.InstantiationException:不能实例类
com.myproject.test.dumy_class;没有空的构造
java.lang.InstantiationException: can't instantiate class com.myproject.test.dumy_class; no empty constructor
,请帮助。
推荐答案
您需要在您的Java类中创建一个空的构造器:
You need to create an empty contructor in your Java class:
public class main {
// Initalize context
Context mContext;
public main(){
}
public main(Context mContext){
this.mContext = mContext;
}
public boolean main() {
Log.d("MYLOG", "main() called successfully when there context is not initialized like above");
// some code here
}
}
这只会调用空构造函数,这可能不是你想要的。
This will only call the empty constructor, which may not be what you want.
另外,你需要选择你想要的构造和参数添加到您的newInstance调用(请参阅related SO质疑这里)像这样:
Alternatively, you need to choose the constructor you want and add a parameter to your newInstance call (see related SO question here) like so:
Class[] cArg = new Class[1];
cArg[0] = Context.class;
classToLoad.getDeclaredConstructor(cArg).newInstance(context);
所以你的非空构造
so your non-empty constructor
public main(Context mContext)
被调用。
这篇关于Android的Java的无法加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!