Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
171 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...