01: /*
02: * Copyright (C) 2004 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 06. April 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.core.util;
13:
14: import java.lang.reflect.Field;
15:
16: /**
17: * Slightly nicer way to find, get and set fields in classes. Wraps standard java.lang.reflect.Field calls but wraps
18: * wraps exception in RuntimeExceptions.
19: *
20: * @author Joe Walnes
21: */
22: public class Fields {
23: public static Field find(Class type, String name) {
24: try {
25: Field result = type.getDeclaredField(name);
26: result.setAccessible(true);
27: return result;
28: } catch (NoSuchFieldException e) {
29: throw new RuntimeException("Could not access "
30: + type.getName() + "." + name + " field");
31: }
32: }
33:
34: public static void write(Field field, Object instance, Object value) {
35: try {
36: field.set(instance, value);
37: } catch (IllegalAccessException e) {
38: throw new RuntimeException("Could not write "
39: + field.getType().getName() + "." + field.getName()
40: + " field");
41: }
42: }
43:
44: public static Object read(Field field, Object instance) {
45: try {
46: return field.get(instance);
47: } catch (IllegalAccessException e) {
48: throw new RuntimeException("Could not read "
49: + field.getType().getName() + "." + field.getName()
50: + " field");
51: }
52: }
53: }
|