view 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
line wrap: on
line source

package de.codedo.java.editor;

import java.lang.reflect.Field;

public class ReflectionUtils
{
	public static Field getField(String fieldName, Object object) throws NoSuchFieldException
	{
		Field field = findField(fieldName, object.getClass());
		field.setAccessible(true);
		return field;
	}

	@SuppressWarnings("unchecked")
	public static <T> T getFieldValue(String fieldName, Object object) throws NoSuchFieldException, IllegalAccessException
	{
		Field field = getField(fieldName, object);
		return (T)field.get(object);
	}
	
	public static void setFieldValue(Object object, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException 
	{
		Field field = getField(fieldName, object);
		field.set(object, value);
	}
	
	private static Field findField(String fieldName, Class<?> clazz) throws NoSuchFieldException
	{
		try
		{
			return clazz.getDeclaredField(fieldName);
		}
		catch (NoSuchFieldException ex)
		{
			// OK, this class does not declare the field. Continue searching the superclass below.
		}

		Class<?> superClass = clazz.getSuperclass();
		if (superClass == null)
		{
			throw new IllegalStateException("Field " + fieldName + " could not be found in object's type hierarchy.");
		}
		return findField(fieldName, superClass);
	}
}