是否可以扫描android类路径注释?

时间:2011-10-02 16:47:13

标签: java android

我想在Android路径中扫描某些注释的类路径。

我只找到了一个解决此问题的方法:http://mindtherobot.com/blog/737/android-hacks-scan-android-classpath/

正如作者写的这个解决方案有效,但有一些局限性。在Android中有没有任何面向未来的方法?任何提供此功能的库?

1 个答案:

答案 0 :(得分:1)

这适用于我使用android 3.0

public static <T extends Annotation> List<Class> getClassesAnnotatedWith(Class<T> theAnnotation){

    // In theory, the class loader is not required to be a PathClassLoader
    PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader();
    Field field = null;
    ArrayList<Class> candidates = new ArrayList<Class>();

    try {
        field = PathClassLoader.class.getDeclaredField("mDexs");
        field.setAccessible(true);
    } catch (Exception e) {
        // nobody promised that this field will always be there
        Log.e(TAG, "Failed to get mDexs field", e);
    }

    DexFile[] dexFile = null;
    try {
        dexFile = (DexFile[]) field.get(classLoader);
    } catch (Exception e) {
        Log.e(TAG, "Failed to get DexFile", e);
    }

    for (DexFile dex : dexFile) {
      Enumeration<String> entries = dex.entries();
      while (entries.hasMoreElements()) {
        // Each entry is a class name, like "foo.bar.MyClass"
        String entry = entries.nextElement();

        // Load the class
        Class<?> entryClass = dex.loadClass(entry, classLoader);
        if (entryClass != null && entryClass.getAnnotation(theAnnotation) != null) {
            Log.d(TAG, "Found: " + entryClass.getName());
            candidates.add(entryClass);
        }
      }
    }

    return candidates;
}    

我还创建了一个来确定一个类是否来自X

public static List<Class> getClassesSuperclassedOf(Class theClass){

    // In theory, the class loader is not required to be a PathClassLoader
    PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader();
    Field field = null;
    ArrayList<Class> candidates = new ArrayList<Class>();

    try {
        field = PathClassLoader.class.getDeclaredField("mDexs");
        field.setAccessible(true);
    } catch (Exception e) {
        // nobody promised that this field will always be there
        Log.e(TAG, "Failed to get mDexs field", e);
    }

    DexFile[] dexFile = null;
    try {
        dexFile = (DexFile[]) field.get(classLoader);
    } catch (Exception e) {
        Log.e(TAG, "Failed to get DexFile", e);
    }

    for (DexFile dex : dexFile) {
      Enumeration<String> entries = dex.entries();
      while (entries.hasMoreElements()) {
        // Each entry is a class name, like "foo.bar.MyClass"
        String entry = entries.nextElement();

        // Load the class
        Class<?> entryClass = dex.loadClass(entry, classLoader);
        if (entryClass != null && entryClass.getSuperclass() == theClass) {
            Log.d(TAG, "Found: " + entryClass.getName());
            candidates.add(entryClass);
        }
      }
    }

    return candidates;
}

享受 - B