comparison src/de/codedo/java/editor/ReflectionUtils.java @ 9:935df68696c0 default tip

Reflection Code in eigene Klasse verschoben.
author Dirk Olmes <dirk.olmes@codedo.de>
date Thu, 15 Oct 2020 12:05:06 +0200
parents
children
comparison
equal deleted inserted replaced
8:778c251baa66 9:935df68696c0
1 package de.codedo.java.editor;
2
3 import java.lang.reflect.Field;
4
5 public class ReflectionUtils
6 {
7 public static Field getField(String fieldName, Object object) throws NoSuchFieldException
8 {
9 Field field = findField(fieldName, object.getClass());
10 field.setAccessible(true);
11 return field;
12 }
13
14 @SuppressWarnings("unchecked")
15 public static <T> T getFieldValue(String fieldName, Object object) throws NoSuchFieldException, IllegalAccessException
16 {
17 Field field = getField(fieldName, object);
18 return (T)field.get(object);
19 }
20
21 public static void setFieldValue(Object object, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException
22 {
23 Field field = getField(fieldName, object);
24 field.set(object, value);
25 }
26
27 private static Field findField(String fieldName, Class<?> clazz) throws NoSuchFieldException
28 {
29 try
30 {
31 return clazz.getDeclaredField(fieldName);
32 }
33 catch (NoSuchFieldException ex)
34 {
35 // OK, this class does not declare the field. Continue searching the superclass below.
36 }
37
38 Class<?> superClass = clazz.getSuperclass();
39 if (superClass == null)
40 {
41 throw new IllegalStateException("Field " + fieldName + " could not be found in object's type hierarchy.");
42 }
43 return findField(fieldName, superClass);
44 }
45 }