我想为Android创建一些插件示例,因此我有3个项目:
外部接口-包含IExternalLib,并生成到externallibinterface.jar文件

  package com.example.externallibinterface;
  public interface IExternalLib {
    public String someMethod( String param );
  }

外部-包含externallibinterface.jarSomeClass implements IExternalLib,生成到externallib.apk
   package com.example.externallib;
   import com.example.externallibinterface.IExternalLib;
   public class SomeClass implements IExternalLib {
       public String someMethod(String arg0) {
           return arg0;
       }
   }

someapp-包含externallibinterface.jar和activity-application的类,我从中加载外部apk和类。
   import com.example.externallibinterface.IExternalLib;
   import dalvik.system.PathClassLoader;

   public class MainActivity extends Activity {

       @Override
       public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);

           String apkToLoad = null;

           String externalPackagePath = "com.example.externallib";
           String externalClassPath = "com.example.externallib.SomeClass";

           try {
               apkToLoad = getPackageManager()
                    .getApplicationInfo( externalPackagePath, MODE_PRIVATE ).sourceDir;
           } catch ( PackageManager.NameNotFoundException e ) {
               e.printStackTrace();
           }

           PathClassLoader pathClassLoader =
                   new PathClassLoader( apkToLoad,
                ClassLoader.getSystemClassLoader() );

           try {
               Class<?> c = Class.forName( externalClassPath, true, pathClassLoader );

               Object someClassInstance = c.newInstance();
                       //exception ClassCastException here
               IExternalLib i = (IExternalLib) someClassInstance;
               i.someMethod( "some string" );
           } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
           } catch (InstantiationException e) {
            e.printStackTrace();
           } catch (IllegalAccessException e) {
            e.printStackTrace();
           } catch ( ClassCastException e ) {
            e.printStackTrace();
           }
       }
   }

但是当我把Object someClassInstance转换成IExternalLib时,我得到ClassCastException
为什么?IExternalLib定义在第三位(inexternallibinterface.jar)。

最佳答案

当不同的类装入器装入类时,可能会发生这种情况。请确保立即构建整个设置,以便只有一个类加载器负责加载类。当您将一个特定的.WAR文件重新部署到现有的系统时,这种情况经常发生。请参阅此处了解更多信息can't cast to implemented interface

10-08 18:02