aboutsummaryrefslogtreecommitdiff
path: root/src/gradlecomp/java/com/amadornes/artifactural/gradle/ReflectionUtils.java
blob: 5dcb9a3cee13f3dd3c617539d607a0b6b0709bd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.amadornes.artifactural.gradle;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.function.UnaryOperator;

public class ReflectionUtils {

    public static <T> void alter(Object target, String name, UnaryOperator<T> operator) {
        try {
            Object prev = target;
            Field f = null;
            for (String n : name.split("\\.")) {
                f = findField(target.getClass(), n);
                if (f == null) throw new IllegalStateException("Could not find '" + name + "'");
                f.setAccessible(true);
                prev = target;
                target = f.get(target);
            }
            if (f == null) throw new IllegalStateException("Could not find '" + name + "'");
            f.set(prev, operator.apply((T) target));
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static Field findField(Class<?> clazz, String name) {
        while (clazz != Object.class) {
            for (Field f : clazz.getDeclaredFields()) {
                if (f.getName().equals(name)) {
                    return f;
                }
            }
            clazz = clazz.getSuperclass();
        }
        return null;
    }

    /**
     * Invokes a method (can be private).
     */
    public static <T> T invoke(Object target, Class<?> type, String name, Object... args) {
        try {
            Method method = type.getDeclaredMethod(name);
            method.setAccessible(true);
            return (T) method.invoke(target, args);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

}