hoochiang2015-10-18 00:04阅读数: 776
java 动态加载jar包
通过动态加载jar包,实现模块插件化
shift + 鼠标右键打开命令行,输入dx --dex --output=qula_dex.jar qula.jar
执行成功后
public class FileUtils {
public static void copyFiles(Context context, String fileName, File desFile) {
InputStream in =null
OutputStream out =null
try {
in = context.getApplicationContext().getAssets().open(fileName)
out =new FileOutputStream(desFile.getAbsolutePath())
byte[] bytes =new byte[1024]
int i
while ((i = in.read(bytes)) != -1){
out.write(bytes,0, i)
}
}catch (IOException e) {
e.printStackTrace()
}finally {
try {
if (in !=null)
in.close()
if (out !=null)
out.close()
}catch (IOException e) {
e.printStackTrace()
}
}
}
public static boolean hasExternalStorage() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
}
/**
* 获取缓存路径
* @param context
* @return 返回缓存文件路径
*/
public static File getCacheDir(Context context) {
File cache
if (hasExternalStorage()) {
cache = context.getExternalCacheDir()
}else {
cache = context.getCacheDir()
}
if (!cache.exists()){
cache.mkdirs()
}
return cache
}
}
/**
* 加载dex文件中的class,并调用其中的sayHello方法
*/
private void loadDexClass() {
File cacheFile = FileUtils.getCacheDir(context)
String internalPath = cacheFile.getAbsolutePath() + File.separator +"qula_dex.jar"
File desFile =new File(internalPath)
try {
if (!desFile.exists()) {
desFile.createNewFile()
FileUtils.copyFiles(context,"qula_dex.jar", desFile)
}
}catch (IOException e) {
e.printStackTrace()
}
//下面开始加载dex class
DexClassLoader dexClassLoader =new DexClassLoader(internalPath,
cacheFile.getAbsolutePath(),null,context.getClassLoader())
try {
//加载的类名为jar文件里面完整类名,写错会找不到此类hh
Class libClazz = dexClassLoader.loadClass("com.justcodeit.xiaoshuo.netbook.BookFactory_qula")
loadBook = (IBookLoadFactory) libClazz.newInstance()
if (loadBook !=null)
Toast.makeText(context,"版本号" +loadBook.getVersion(), Toast.LENGTH_LONG).show()
}catch (Exception e) {
e.printStackTrace()
}
}
选中要加载jar的工程,右击出现菜单Build Path --->Configure Build Path 出现Properties 选择JavaBuildPath Libraries 点击Add External JARs......就可加载你要加载的jar包了,jar包加载到工程里面的是Jar的路径 并没有把Jar包里面的内容复制进去,如果你把工程复制到另一台计算机上的运行又得重新加载jar包。。。。。。这是个人理解,不知道是否能解决你的问题。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)