2

我想为 android 创建一些插件示例,所以我有 3 个项目:

ExternalLibInterface - 包含IExternalLib并构建到externallibinterface.jar文件

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

ExternalLib - 包含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和活动类 - 我从中加载外部 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得到. 为什么?被定义在第 3 位 (in )。IExternalLibClassCastExceptionIExternalLibexternallibinterface.jar

4

2 回答 2

2

尝试以下操作:

Class<? extends IExternalLib> l_clazz; // our expected class
Class<?> clazz = Class.forName("com.example.externallib.SomeClass"); // our unknown class

// check if our unknown class can be cast to our expected class
if ((l_clazz = clazz.asSubclass(IExternalLib.class)) != null) {
    IExternalLib i = l_clazz.newInstance();
    i.someMethod( "some string" );
}
于 2012-09-12T07:50:22.573 回答
1

当不同的类加载器加载类时可能会发生这种情况。确保一次构建整个设置,以便只有一个类加载器负责加载类。当您只是将特定的 .war 文件重新部署到现有系统上时,这种情况经常发生。请参阅此以获得更多见解无法转换为已实现的接口

于 2014-01-22T11:37:08.403 回答