Debian Codegraph @

instant-run/instant-run-runtime/src/main/java/com/android/tools/fd/runtime/AbstractPatchesLoaderImpl.java

raw
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.tools.fd.runtime;
18
19
20 import static com.android.tools.fd.common.Log.logging;
21
22 import java.lang.reflect.Field;
23 import java.util.logging.Level;
24
25 public abstract class AbstractPatchesLoaderImpl implements PatchesLoader {
26
27 public abstract String[] getPatchedClasses();
28
29 @Override
30 public boolean load() {
31 try {
32 for (String className : getPatchedClasses()) {
33 ClassLoader cl = getClass().getClassLoader();
34 Class<?> aClass = cl.loadClass(className + "$override");
35 Object o = aClass.newInstance();
36 Class<?> originalClass = cl.loadClass(className);
37 Field changeField = originalClass.getDeclaredField("$change");
38 // force the field accessibility as the class might not be "visible"
39 // from this package.
40 changeField.setAccessible(true);
41
42 // If there was a previous change set, mark it as obsolete:
43 Object previous = changeField.get(null);
44 if (previous != null) {
45 Field isObsolete = previous.getClass().getDeclaredField("$obsolete");
46 if (isObsolete != null) {
47 isObsolete.set(null, true);
48 }
49 }
50 changeField.set(null, o);
51
52 if (logging != null && logging.isLoggable(Level.FINE)) {
53 logging.log(Level.FINE, String.format("patched %s", className));
54 }
55 }
56 } catch (Exception e) {
57 if (logging != null) {
58 logging.log(Level.SEVERE, String.format("Exception while patching %s", "foo.bar"), e);
59 }
60 return false;
61 }
62 return true;
63 }
64 }