Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Android java unable to load class

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...