Search in sources :

Example 1 with DynamicallyComponent

use of org.mule.runtime.core.internal.component.DynamicallyComponent in project mule by mulesoft.

the class AnnotatedObjectInvocationHandler method removeDynamicAnnotations.

/**
 * Returns a newly built object containing the state of the given {@code annotated} object, but without any of its annotations.
 * <p>
 * This is useful when trying to use the base object in some scenarios where the object is introspected, to avoid the
 * dynamically added stuff to interfere with that introspection.
 * <p>
 * Note that there is no consistent state kept between the {@code annotated} and the returned objects. After calling this
 * method, the {@code annotated} object should be discarded (unless it is immutable, which wouldn't cause any problems)
 *
 * @param annotated the object to remove dynamic stuff from
 * @return a newly built object.
 */
public static <T, A> T removeDynamicAnnotations(A annotated) {
    if (annotated instanceof DynamicallyComponent) {
        Class<?> baseClass = annotated.getClass().getSuperclass();
        Map<String, Field> fieldsByName = new HashMap<>();
        Class<?> currentClass = baseClass;
        while (currentClass != Object.class) {
            Field[] targetFields = currentClass.getDeclaredFields();
            for (Field field : targetFields) {
                if (!isStatic(field.getModifiers()) && !fieldsByName.containsKey(field.getName())) {
                    fieldsByName.put(field.getName(), field);
                }
            }
            currentClass = currentClass.getSuperclass();
        }
        try {
            T base = (T) baseClass.newInstance();
            for (Field field : fieldsByName.values()) {
                boolean acc = field.isAccessible();
                field.setAccessible(true);
                try {
                    field.set(base, field.get(annotated));
                } finally {
                    field.setAccessible(acc);
                }
            }
            return base;
        } catch (Exception e) {
            throw new MuleRuntimeException(e);
        }
    } else {
        return (T) annotated;
    }
}
Also used : Field(java.lang.reflect.Field) HashMap(java.util.HashMap) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException) DynamicallyComponent(org.mule.runtime.core.internal.component.DynamicallyComponent) MuleRuntimeException(org.mule.runtime.api.exception.MuleRuntimeException)

Aggregations

Field (java.lang.reflect.Field)1 HashMap (java.util.HashMap)1 MuleRuntimeException (org.mule.runtime.api.exception.MuleRuntimeException)1 DynamicallyComponent (org.mule.runtime.core.internal.component.DynamicallyComponent)1