1. Activity的加载流程
在ActivityThread中的 performLaunchActivity()方法中调用 newActivity()方法,
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
然后点击 newActivity()方法,进入:
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
// 通过 ClassLoader找到 Activity的 class,然后利用反射实例化 TestActivity对象
return (Activity)cl.loadClass(className).newInstance();
}
也就是说我们的 Activity是通过来创建的,所有类的加载都是通过 ClassLoader.findName来找到Class来加载;
(Activity)cl.loadClass(className).newInstance();
上边的ClassLoader 就是 PathClassLoader ,继承关系:
PathClassLoader -> BaseDexClassLoader -> ClassLoader
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
long t1 = System.nanoTime();
c = findClass(name);
}
}
return c;
}
有这段代码可知,最终调用的是findClass(name);