안녕하세요 내 안드로이드 앱에서 클래스를로드 할 수 없습니다. 기본 클래스를로드 할 수 있지만 해당 클래스에서 컨텍스트를 초기화하면로드 할 수 없습니다.
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
}
}
내 클래스 로딩 코드
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();
}
내가 얻은 예외 :
java.lang.InstantiationException : com.myproject.test.dumy_class 클래스를 인스턴스화 할 수 없습니다. 빈 생성자 없음
그래서 제발 도와주세요.
Java 클래스에 빈 생성자를 만들어야합니다.
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
}
}
이것은 당신이 원하는 것이 아닐 수도있는 빈 생성자 만 호출 할 것입니다.
또는 원하는 생성자를 선택하고 다음과 같이 newInstance 호출에 매개 변수를 추가해야합니다 ( 여기 관련 SO 질문 참조 ).
Class[] cArg = new Class[1];
cArg[0] = Context.class;
classToLoad.getDeclaredConstructor(cArg).newInstance(context);
그래서 비어 있지 않은 생성자
public main(Context mContext)
호출됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다