G
G
gibbonchik2016-04-01 12:11:17
Java
gibbonchik, 2016-04-01 12:11:17

How to use jar dynamically?

There is a simple .jar library, it has one class com.example.myclass:

package com.example;

public class myclass
{
  public int Summ(int a, int b)
  {
    return a + b;
  }
}

and manifest:
Manifest-Version: 1.0
Main-Class: com.example.myclass

69901fa94b8948db911a9f9c2f7a5089.png
From my android app, I'm trying to call the "summ" function with the following code:
String dexPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/lib.jar";
        String dexOutputDir = getApplicationInfo().dataDir;
        DexClassLoader pathClassLoader = new DexClassLoader(dexPath, dexOutputDir, null, this
                .getClass().getClassLoader());
        try {
            Class<?> class1 = pathClassLoader.loadClass("com.example.myclass");
            Object object = class1.newInstance();
            Class[] params = new Class[2];
            params[0] = Integer.TYPE;
            params[1] = Integer.TYPE;
            Method action = class1.getMethod("Summ", params);
            Integer ret = (Integer) action.invoke(object, 12, 13);
            tv.setText("method : " + action.getName() + ", return :" + ret);
        } catch (Exception e) {
            tv.setText("error : " + e.getMessage());
        }

But the error "Didn't find class" occurs.
Tell me, please, maybe I have the wrong structure of the jar file or I call the method incorrectly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gibbonchik, 2016-04-13
@gibbonchik

Found a solution:

File f = new File("/sdcard/MyFavorite/mygame.jar");
DexClassLoader u = new DexClassLoader(f.toURI().toURL().toString(), getDir("libs", MODE_PRIVATE).getAbsolutePath(), null, ClassLoader.getSystemClassLoader());
Class c = u.loadClass("com.example.myclass");
Object object = c.newInstance();
Class[] params = new Class[2];
params[0] = Integer.TYPE;
params[1] = Integer.TYPE;
Method action = c.getMethod("Summ", params);
Integer ret = (Integer) action.invoke(object, 12, 13);
Log.d("DEBUG","method : " + action.getName() + ", return :" + ret);

, but we slightly change the .jar file itself. instead of classes (com/example/myclass.class) you need to put one classes.dex file.
It is created with the following command:
dx.bat --dex --verbose --output .\libgame\classes.dex .\libgame

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question