OLD | NEW |
| (Empty) |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 package org.chromium.webapk.shell_apk; | |
6 | |
7 import java.lang.reflect.Array; | |
8 import java.lang.reflect.Field; | |
9 | |
10 /** | |
11 * Reflection helper methods. | |
12 */ | |
13 final class Reflect { | |
14 /** | |
15 * Sets the value of an object's field (even if it's not visible). | |
16 * | |
17 * @param instance The object containing the field to set. | |
18 * @param name The name of the field to set. | |
19 * @param value The new value for the field. | |
20 */ | |
21 static void setField(Object instance, String name, Object value) | |
22 throws ReflectiveOperationException { | |
23 Field field = findField(instance, name); | |
24 field.setAccessible(true); | |
25 field.set(instance, value); | |
26 } | |
27 | |
28 /** | |
29 * Retrieves the value of an object's field (even if it's not visible). | |
30 * | |
31 * @param instance The object containing the field to set. | |
32 * @param name The name of the field to set. | |
33 * @return The field's value. Primitive values are returned as their boxed | |
34 * type. | |
35 */ | |
36 static Object getField(Object instance, String name) throws ReflectiveOperat
ionException { | |
37 Field field = findField(instance, name); | |
38 field.setAccessible(true); | |
39 return field.get(instance); | |
40 } | |
41 | |
42 /** | |
43 * Concatenates two arrays into a new array. The arrays must be of the same | |
44 * type. | |
45 */ | |
46 static Object[] concatArrays(Object[] left, Object[] right) { | |
47 Object[] result = (Object[]) Array.newInstance( | |
48 left.getClass().getComponentType(), left.length + right.length); | |
49 System.arraycopy(left, 0, result, 0, left.length); | |
50 System.arraycopy(right, 0, result, left.length, right.length); | |
51 return result; | |
52 } | |
53 | |
54 private static Field findField(Object instance, String name) throws NoSuchFi
eldException { | |
55 boolean isStatic = instance instanceof Class; | |
56 Class<?> clazz = isStatic ? (Class<?>) instance : instance.getClass(); | |
57 for (; clazz != null; clazz = clazz.getSuperclass()) { | |
58 try { | |
59 return clazz.getDeclaredField(name); | |
60 } catch (NoSuchFieldException e) { | |
61 // Need to look in the super class. | |
62 } | |
63 } | |
64 throw new NoSuchFieldException("Field " + name + " not found in " + inst
ance.getClass()); | |
65 } | |
66 } | |
OLD | NEW |