KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > core > util > Fields


1 package com.thoughtworks.xstream.core.util;
2
3 import java.lang.reflect.Field JavaDoc;
4
5 /**
6  * Slightly nicer way to find, get and set fields in classes. Wraps standard java.lang.reflect.Field calls but wraps
7  * wraps exception in RuntimeExceptions.
8  *
9  * @author Joe Walnes
10  */

11 public class Fields {
12     public static Field JavaDoc find(Class JavaDoc type, String JavaDoc name) {
13         try {
14             Field JavaDoc result = type.getDeclaredField(name);
15             result.setAccessible(true);
16             return result;
17         } catch (NoSuchFieldException JavaDoc e) {
18             throw new RuntimeException JavaDoc("Could not access " + type.getName() + "." + name + " field");
19         }
20     }
21
22     public static void write(Field JavaDoc field, Object JavaDoc instance, Object JavaDoc value) {
23         try {
24             field.set(instance, value);
25         } catch (IllegalAccessException JavaDoc e) {
26             throw new RuntimeException JavaDoc("Could not write " + field.getType().getName() + "." + field.getName() + " field");
27         }
28     }
29
30     public static Object JavaDoc read(Field JavaDoc field, Object JavaDoc instance) {
31         try {
32             return field.get(instance);
33         } catch (IllegalAccessException JavaDoc e) {
34             throw new RuntimeException JavaDoc("Could not read " + field.getType().getName() + "." + field.getName() + " field");
35         }
36     }
37 }
38
Popular Tags