OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 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.base; |
| 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) throws NoSu
chFieldException { |
| 22 Field field = findField(instance, name); |
| 23 try { |
| 24 field.setAccessible(true); |
| 25 field.set(instance, value); |
| 26 } catch (IllegalAccessException e) { |
| 27 // This shouldn't happen. |
| 28 } |
| 29 } |
| 30 |
| 31 /** |
| 32 * Retrieves the value of an object's field (even if it's not visible). |
| 33 * |
| 34 * @param instance The object containing the field to set. |
| 35 * @param name The name of the field to set. |
| 36 * @return The field's value. Primitive values are returned as their boxed t
ype. |
| 37 */ |
| 38 static Object getField(Object instance, String name) throws NoSuchFieldExcep
tion { |
| 39 Field field = findField(instance, name); |
| 40 try { |
| 41 field.setAccessible(true); |
| 42 return field.get(instance); |
| 43 } catch (IllegalAccessException e) { |
| 44 // This shouldn't happen. |
| 45 } |
| 46 return null; |
| 47 } |
| 48 |
| 49 /** |
| 50 * Concatenates two arrays into a new array. The arrays must be of the same
type. |
| 51 */ |
| 52 static Object[] concatArrays(Object[] left, Object[] right) { |
| 53 Object[] result = (Object[]) (Array.newInstance( |
| 54 left.getClass().getComponentType(), left.length + right.length))
; |
| 55 System.arraycopy(left, 0, result, 0, left.length); |
| 56 System.arraycopy(right, 0, result, left.length, right.length); |
| 57 return result; |
| 58 } |
| 59 |
| 60 /** |
| 61 * Finds the Field with the given name for the given object, traversing supe
rclasses if |
| 62 * necessary. |
| 63 */ |
| 64 private static Field findField(Object instance, String name) throws NoSuchFi
eldException { |
| 65 for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.
getSuperclass()) { |
| 66 try { |
| 67 return clazz.getDeclaredField(name); |
| 68 } catch (NoSuchFieldException e) { |
| 69 } |
| 70 } |
| 71 throw new NoSuchFieldException("Field " + name + " not found in " + inst
ance.getClass()); |
| 72 } |
| 73 } |
OLD | NEW |