Last active
February 10, 2017 07:40
-
-
Save afshin-hoseini/aa04a5031d02e27caa793e059e51dcf8 to your computer and use it in GitHub Desktop.
Reflection methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
*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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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