Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Last active January 7, 2017 05:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afshin-hoseini/b301d7d9f6db1e9d09da6ed0f7870fdc to your computer and use it in GitHub Desktop.
Save afshin-hoseini/b301d7d9f6db1e9d09da6ed0f7870fdc to your computer and use it in GitHub Desktop.
Finding all classes available in an android application.
//To list all methods in android application
public void listAllClasses() {
try {
DexFile df = new DexFile(getPackageCodePath());
for (Enumeration<String> iter = df.entries(); iter.hasMoreElements();) {
String classPath = iter.nextElement();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//To get generic types defined in a an object initilization
/*
//Assume we have some object definition like this:
CallbackListener callbacklistener = new CallbackListener<SomeController.Response>();
//We have to do this in order to get type of generic type defined in
Class responseType = (Class<? extends Response>) ((ParameterizedType) callbackListener.getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
*/
//To find all classes of a specific type
public static Set<Class> getClassesOfType(@NonNull Class typeOfClass, @NonNull String inPackageName, @NonNull Context context, boolean onlyIncludeSubclasses) {
Set<Class> classes = new HashSet<>();
try {
DexFile df = new DexFile(context.getPackageCodePath());
for (Enumeration<String> iter = df.entries(); iter.hasMoreElements();) {
String classPath = iter.nextElement();
if(classPath.startsWith(inPackageName)) {
Class main = Class.forName(classPath);
Class c = main;
do {
if(c.getName().equals(typeOfClass.getName())) {
if(onlyIncludeSubclasses && c == main)
break;
classes.add(main);
break;
}
c = c.getSuperclass();
} while ( c != null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment