Java Reflection Field Set setField(Field field, Object target, Object value)

Here you can find the source of setField(Field field, Object target, Object value)

Description

set Field

License

Apache License

Declaration

public static void setField(Field field, Object target, Object value) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.UndeclaredThrowableException;

public class Main {
    public static void setField(Field field, Object target, Object value) {
        try {/*  w w  w  .j ava  2 s .c om*/
            field.set(target, value);
        } catch (IllegalAccessException ex) {
            handleReflectionException(ex);
            throw new IllegalStateException(
                    "Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
        }
    }

    public static void handleReflectionException(Exception ex) {
        if (ex instanceof NoSuchMethodException) {
            throw new IllegalStateException("Method not found: " + ex.getMessage());
        }
        if (ex instanceof IllegalAccessException) {
            throw new IllegalStateException("Could not access method: " + ex.getMessage());
        }
        if (ex instanceof InvocationTargetException) {
            handleInvocationTargetException((InvocationTargetException) ex);
        }
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        throw new UndeclaredThrowableException(ex);
    }

    public static void handleInvocationTargetException(InvocationTargetException ex) {
        rethrowRuntimeException(ex.getTargetException());
    }

    public static void rethrowRuntimeException(Throwable ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        if (ex instanceof Error) {
            throw (Error) ex;
        }
        throw new UndeclaredThrowableException(ex);
    }
}

Related

  1. setField(Field field, Object target, Object value)
  2. setField(Field field, Object target, Object value)
  3. setField(Field field, Object target, Object value)
  4. setField(Field field, Object target, Object value)
  5. setField(Field field, Object target, Object value)
  6. setField(Field field, T newValue, Object instance)
  7. setField(Field field, U instance, Object value)
  8. setField(final Field field, final Object instance, final Object value)
  9. setField(final Field field, final Object object, final Object value)