public void testAA(){ try { Class c = Class.forName("com.ymfa"); Field f = c.getDeclaredField("test_var"); Integer i = (Integer) f.get(null); Android.util.Log.i("TAG",i+""); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
程序B:public class ShareId_B extends Activity { static int test_var = 10; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); }} 情景2: 两个独立的APK,配置成同一个进程A:public class Ymf { public static int a = 10; } B:public class ShareId_B extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //PathClassLoader loader = new PathClassLoader("/data/app/com.ymf.a.apk", ClassLoader.getSystemClassLoader()); Context context = null; try { context = createPackageContext("com.ymf.a", Context.CONTEXT_INCLUDE_CODE|Context.CONTEXT_IGNORE_SECURITY); } catch (NameNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Class c = null; try { c = context.getClassLoader().loadClass("com.ymf.a.Ymf");
android.util.Log.i("TAG",context.getClassLoader().toString()+""); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Field f = null; try { f = c.getDeclaredField("a"); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } int o = 0; try { o = (Integer) f.get(null); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } android.util.Log.i("TAG",o+"");