Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Last active February 10, 2017 07:40
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/aa04a5031d02e27caa793e059e51dcf8 to your computer and use it in GitHub Desktop.
Save afshin-hoseini/aa04a5031d02e27caa793e059e51dcf8 to your computer and use it in GitHub Desktop.
Reflection methods
/**
*This method searchs for classes of type DatabaseManager and then checks if they have any public static method annotated
*with @createTables. If exists this will invoke them to make tables database.
*/
protected boolean createTables(SQLiteDatabase db, DatabaseType databaseType)
{
boolean success = true;
if(databaseType == DatabaseType.AppDb) {
Set<Class> subclassesOfDatabaseManager = Reflection.getClassesOfType(DatabaseManager.class, "ir.afe.spot", context, true);
if(subclassesOfDatabaseManager != null) {
for(Class c : subclassesOfDatabaseManager) {
try {
for(Method method : c.getMethods()) {
if(method.isAnnotationPresent(CreatesTable.class)) {
method.invoke(this, db);
break;
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
return success;
}
public class Reflection {
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