我有一个线程,它根据系统的具体实现为它需要的资源加载不同的类。我的实现是在 Android 上,我有一个类可以返回我的实现所需的特定类。我似乎能够很好地加载该类,但是当我尝试将它分配给我的主线程中的对象时,它给了我一个 ClassCastException。以下是片段:
在我的主线程中,我这样做:
try {
grammarProcessor = config.loadObject(GrammarProcessor.class);
这给了我这个堆栈跟踪:
E/AndroidRuntime(6682): FATAL EXCEPTION: JVoiceXmlMain
E/AndroidRuntime(6682): java.lang.ClassCastException: org.jvoicexml.android.JVoiceXmlGrammarProcessor
E/AndroidRuntime(6682): at org.jvoicexml.JVoiceXmlMain.run(JVoiceXmlMain.java:321)
GrammarProcessor
是一个接口,JVoiceXmlGrammarProcessor
是我加载和实现该接口的类。加载代码如下:
else if(baseClass == GrammarProcessor.class){
String packageName = "org.jvoicexml.android";
String className = "org.jvoicexml.android.JVoiceXmlGrammarProcessor";
String apkName = null;
Class<?> handler = null;
T b = null;
try {
PackageManager manager = callManagerContext.getPackageManager();
ApplicationInfo info= manager.getApplicationInfo(packageName, 0);
apkName= info.sourceDir;
} catch (NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return null;
}
PathClassLoader myClassLoader =
new dalvik.system.PathClassLoader(
apkName,
ClassLoader.getSystemClassLoader());
try {
handler = Class.forName(className, true, myClassLoader);
return (T) handler.newInstance();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
调试时,我检查从 load 方法返回的内容,它是一个带有 id 号的对象。如果我点击它,它会说org.jvoicexml.android.JVoiceXmlGrammarProcessor@40565820
,下拉菜单会显示 aJVoiceXmlGrammarProcessor
应该有的两个私有字段,所以看起来它已经加载好了。有任何想法吗?