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
}
}
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: can't instantiate class com.myproject.test.dumy_class; no empty constructor
so please help .
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.
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)
is called.