Esempio n. 1
0
  private void scanForModel(Context context) throws IOException {
    String packageName = context.getPackageName();
    String sourcePath = context.getApplicationInfo().sourceDir;
    List<String> paths = new ArrayList<String>();

    if (sourcePath != null && !(new File(sourcePath).isDirectory())) {
      DexFile dexfile = new DexFile(sourcePath);
      Enumeration<String> entries = dexfile.entries();

      while (entries.hasMoreElements()) {
        paths.add(entries.nextElement());
      }
    }
    // Robolectric fallback
    else {
      ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
      Enumeration<URL> resources = classLoader.getResources("");

      while (resources.hasMoreElements()) {
        String path = resources.nextElement().getFile();
        if (path.contains("bin") || path.contains("classes")) {
          paths.add(path);
        }
      }
    }

    for (String path : paths) {
      File file = new File(path);
      scanForModelClasses(file, packageName, context.getClassLoader());
    }
  }
Esempio n. 2
0
  public void scan() throws IOException, ClassNotFoundException, NoSuchMethodException {
    long timeBegin = System.currentTimeMillis();

    PathClassLoader classLoader = (PathClassLoader) getContext().getClassLoader();
    // PathClassLoader classLoader = (PathClassLoader)
    // Thread.currentThread().getContextClassLoader();//This also works good
    DexFile dexFile = new DexFile(getContext().getPackageCodePath());
    Enumeration<String> classNames = dexFile.entries();
    while (classNames.hasMoreElements()) {
      String className = classNames.nextElement();
      if (isTargetClassName(className)) {
        // Class<?> aClass = Class.forName(className);//java.lang.ExceptionInInitializerError
        // Class<?> aClass = Class.forName(className, false, classLoader);//tested on
        // 魅蓝Note(M463C)_Android4.4.4 and Mi2s_Android5.1.1
        Class<?> aClass =
            classLoader.loadClass(
                className); // tested on 魅蓝Note(M463C)_Android4.4.4 and Mi2s_Android5.1.1
        if (isTargetClass(aClass)) {
          onScanResult(aClass);
        }
      }
    }

    long timeEnd = System.currentTimeMillis();
    long timeElapsed = timeEnd - timeBegin;
    Log.d(TAG, "scan() cost " + timeElapsed + "ms");
  }
  @Override
  public <T> Collection<Class<? extends T>> getDescendants(
      Class<T> parentType, String packageName) {
    List<Class<? extends T>> result = new ArrayList<Class<? extends T>>();

    Enumeration<String> entries = dexFile.entries();
    while (entries.hasMoreElements()) {
      String className = entries.nextElement();
      if (isInPackage(className, packageName) && !isGenerated(className)) {
        Class<? extends T> clazz = loadClass(className);
        if (clazz != null && !parentType.equals(clazz) && parentType.isAssignableFrom(clazz)) {
          result.add(clazz.asSubclass(parentType));
        }
      }
    }
    return result;
  }
Esempio n. 4
0
  /**
   * 获取某一个包名下的所有类名
   *
   * @param context
   * @param packageName
   * @return
   * @throws IOException
   */
  public static List<String> getPackageAllClassName(Context context, String packageName)
      throws IOException {
    String sourcePath = context.getApplicationInfo().sourceDir;
    List<String> paths = new ArrayList<String>();

    if (sourcePath != null) {
      DexFile dexfile = new DexFile(sourcePath);
      Enumeration<String> entries = dexfile.entries();

      while (entries.hasMoreElements()) {
        String element = entries.nextElement();
        if (element.contains(packageName)) {
          paths.add(element);
        }
      }
    }

    return paths;
  }
Esempio n. 5
0
  /* Scans all classes accessible from the context class loader which belong to the given package and subpackages.
   *
   * @param packageName The base package
   * @return The classes
   * @throws ClassNotFoundException
   * @throws IOException
   */
  @SuppressWarnings("unchecked")
  private static List<String> getClasses(String packageName, Context c) throws IOException {
    ArrayList<String> classNames = new ArrayList<String>();

    String zpath = c.getApplicationInfo().sourceDir;

    if (zpath == null) {
      zpath = "/data/app/org.odk.collect.apk";
    }

    DexFile df = new DexFile(new File(zpath));
    for (Enumeration<String> en = df.entries(); en.hasMoreElements(); ) {
      String cn = en.nextElement();
      if (cn.startsWith(packageName) && !cn.contains(".test.")) {
        try {
          Class prototype = Class.forName(cn);
          if (prototype.isInterface()) {
            continue;
          }
          boolean emptyc = false;
          for (Constructor<?> cons : prototype.getConstructors()) {
            if (cons.getParameterTypes().length == 0) {
              emptyc = true;
            }
          }
          if (!emptyc) {
            continue;
          }
          if (Externalizable.class.isAssignableFrom(prototype)) {
            classNames.add(cn);
          }
        } catch (Throwable e) {
          // nothing should every make this crash
        }
      }
    }

    return classNames;
  }
  private static ArrayList<Object> reloadInterface(
      Context c, Activity a, String interfaceName, String version) {

    ArrayList<Object> loadedInterfaceDetails = null;

    try {
      Context applicationContext = c;
      String fName = interfaceName + "_v" + version + ".apk";

      String fullJARPath = applicationContext.getFilesDir().getPath().toString() + "/";
      fullJARPath += fName;

      File file = new File(fullJARPath);
      file.setReadable(true, false);

      URL fileUrl;
      fileUrl = file.toURL();
      if (!file.exists()) {
        throw new Exception("File " + fName + " not found");
      }

      ClassLoader cl = c.getClassLoader();

      DexFile df =
          DexFile.loadDex(
              file.getAbsolutePath(),
              c.getFilesDir().getAbsolutePath() + "/outputdexcontainer_" + interfaceName + ".dex",
              0);

      Class clazz = df.loadClass("com/sdp/deviceinterfaces/" + interfaceName, cl);

      p("Loading inner classes for: " + interfaceName);
      try {
        String prefix = "com.sdp.deviceinterfaces." + interfaceName + "$";
        Enumeration<String> entries = df.entries();
        while (entries.hasMoreElements()) {
          String nn = entries.nextElement();
          if (nn.contains(prefix)) {
            String innerClassPath = nn.replace(".", "/");
            p("Loading Also: " + innerClassPath);
            try {
              df.loadClass(innerClassPath, clazz.getClassLoader());
            } catch (Exception e) {
              p("Error while loading: " + innerClassPath + ", " + e.toString());
            }
          }
        }
        p("Inner classes loaded too");
      } catch (Exception e) {
        p("Error while loading innerclasses: " + e.toString());
      }

      Object whatInstance = clazz.newInstance();

      try {
        Method myMethod1 = clazz.getMethod("setApplicationContext", new Class[] {Context.class});
        myMethod1.invoke(whatInstance, new Object[] {c});

      } catch (Exception e) {
        p("Error adding Application Context: " + e.toString() + ", ");
        return null;
      }

      // Special cases
      try {
        Method setActionMethod = clazz.getMethod("setActivity", new Class[] {Activity.class});
        setActionMethod.invoke(whatInstance, new Object[] {a});

      } catch (Exception e) {
        p("Error adding Activity: " + e.toString() + ", ");
      }

      loadedInterfaceDetails = new ArrayList<Object>();
      loadedInterfaceDetails.add(interfaceName);
      loadedInterfaceDetails.add(clazz);
      loadedInterfaceDetails.add(whatInstance);
      return loadedInterfaceDetails;
    } catch (Exception e) {
      p("Error while loading class: " + interfaceName + ", " + e.toString());
      return null;
    }
  }
 /**
  * Retrieves the entry names from given {@link DexFile}.
  *
  * <p>Exposed for unit testing.
  *
  * @param dexFile
  * @return {@link Enumeration} of {@link String}s
  */
 Enumeration<String> getDexEntries(DexFile dexFile) {
   return dexFile.entries();
 }