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

我想扫描类路径以获取Android中的某些注释。

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

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

这适用于我使用Android 3.0

public static  List getClassesAnnotatedWith(Class theAnnotation){ // In theory, the class loader is not required to be a PathClassLoader PathClassLoader classLoader = (PathClassLoader) Thread.currentThread().getContextClassLoader(); Field field = null; ArrayList candidates = new ArrayList(); 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 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 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 candidates = new ArrayList(); 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 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