热更新
生成更新jar包
调用jar包
public class ReflectUtil {
public static void installPatch(Application application, File patchFile){
if (!patchFile.exists()){
return;
}
ClassLoader classLoader = application.getClassLoader();
try {
Field pathListField = findField(classLoader, "pathList");
Object pathList = pathListField.get(classLoader);
List<File> files = new ArrayList<>();
files.add(patchFile);
File dexOutputDir = application.getCodeCacheDir();
ArrayList<IOException> suggestExceptions = new ArrayList<>();
Method makePathElements = findMethod(pathList, "makePathElements", List.class, File.class, List.class);
Object[] patchElements = (Object[]) makePathElements.invoke(pathList, files, dexOutputDir, suggestExceptions);
Field dexElementField = findField(pathList, "dexElements");
Object[] dexElements = (Object[])dexElementField.get(pathList);
Object[] newElements = (Object[]) Array.newInstance(patchElements.getClass().getComponentType(), patchElements.length + dexElements.length);
System.arraycopy(patchElements, 0, newElements, 0, patchElements.length);
System.arraycopy(dexElements, 0, newElements, patchElements.length, dexElements.length);
dexElementField.set(pathList, newElements);
Log.e("chy", "aa");
}
catch (Exception e){
Toast.makeText(application, e.toString(), Toast.LENGTH_LONG).show();
}
}
public static Field findField(Object instance, String name){
Class<?> cls = instance.getClass();
while (cls != Object.class){
try {
Field field = cls.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (Exception e){
}
cls = cls.getSuperclass();
}
throw new RuntimeException(name + " filed not found");
}
public static Method findMethod(Object instance, String name, Class<?>... parameterType){
Class<?> cls = instance.getClass();
while (cls != Object.class){
try {
Method method = cls.getDeclaredMethod(name, parameterType);
method.setAccessible(true);
return method;
}
catch (Exception e){
}
cls = cls.getSuperclass();
}
throw new RuntimeException(name + " method not found");
}
}
备注:一定要注意文件权限