Skip to content

Commit

Permalink
Fallback class loader for Robolectric
Browse files Browse the repository at this point in the history
Closes #96
  • Loading branch information
Huu Nguyen committed Jul 8, 2014
1 parent 5c25fec commit 3c47b24
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions library/src/com/orm/SugarDb.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import static com.orm.SugarConfig.getDatabaseVersion;
import static com.orm.SugarConfig.getDebugEnabled;
Expand All @@ -32,11 +37,7 @@ public SugarDb(Context context) {
private <T extends SugarRecord<?>> List<T> getDomainClasses(Context context) {
List<T> domainClasses = new ArrayList<T>();
try {
Enumeration<?> allClasses = getAllClasses(context);

while (allClasses.hasMoreElements()) {
String className = (String) allClasses.nextElement();

for (String className : getAllClasses(context)) {
if (className.startsWith(SugarConfig.getDomainPackageName(context))) {
T domainClass = getDomainClass(className, context);
if (domainClass != null) domainClasses.add(domainClass);
Expand Down Expand Up @@ -84,10 +85,26 @@ private <T extends SugarRecord<?>> T getDomainClass(String className, Context co

}

private Enumeration<?> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
private List<String> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
String path = getSourcePath(context);
DexFile dexfile = new DexFile(path);
return dexfile.entries();
List<String> classNames = new ArrayList<String>();
try {
DexFile dexfile = new DexFile(path);
Enumeration<String> dexEntries = dexfile.entries();
while (dexEntries.hasMoreElements()) {
classNames.add(dexEntries.nextElement());
}
} catch (NullPointerException e) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> urls = classLoader.getResources("");
while (urls.hasMoreElements()) {
String urlPath = urls.nextElement().getFile();
if (urlPath.contains("bin") || urlPath.contains("classes")) {
classNames.add(urlPath);
}
}
}
return classNames;
}

private String getSourcePath(Context context) throws PackageManager.NameNotFoundException {
Expand Down

0 comments on commit 3c47b24

Please sign in to comment.