aboutsummaryrefslogtreecommitdiff
path: root/src/gradlecomp/java/com/amadornes/artifactural/gradle/ReflectionUtils.java
blob: d3078d5ba3ffd8bc6cf95eb918596e499c6bd218 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
 * Artifactural
 * Copyright (c) 2018.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation version 2.1
 * of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

package com.amadornes.artifactural.gradle;

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

public class ReflectionUtils {

    @SuppressWarnings("unchecked")
    public static <T> void alter(Object target, String name, UnaryOperator<T> operator) {
        try {
            int idx = name.lastIndexOf('.');
            if (idx != -1) {
                target = drillField(target, name.substring(0, idx));
                if (target == null) throw new IllegalStateException("Could not find field '" + name + "'");
                name = name.substring(idx + 1);
            }
            Field f = findField(target.getClass(), name);
            if (f == null) throw new IllegalStateException("Could not find '" + name + "'");

            T oldV = (T)f.get(target);
            T newV = operator.apply(oldV);
            f.set(target, newV);

            if (f.get(target) != newV) {
                throw new IllegalStateException("Failed to set new value on " + f.getDeclaringClass().getName() + "." + f.getName());
            }
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }

    private static Object drillField(Object obj, String path) {
        for (String name : path.split("\\.")) {
            if (obj == null) return null;
            Field f = findField(obj.getClass(), name);
            if (f == null) return null;
            try {
                obj = f.get(obj);
            } catch (IllegalAccessException e) {
                return null;
            }
        }
        return obj;
    }

    private static Field findField(Class<?> clazz, String name) {
        while (clazz != Object.class) {
            for (Field f : clazz.getDeclaredFields()) {
                if (f.getName().equals(name)) {
                    f.setAccessible(true);
                    if (!definalize(f)) {
                        System.out.println("Could not definalize field " + f.getDeclaringClass().getName() + "." + f.getName() + " Exception ate, lets see if it works");
                    }
                    return f;
                }
            }
            clazz = clazz.getSuperclass();
        }
        return null;
    }

    private static Field MODIFIER_ACCESS = null;
    private static boolean accessAttempted = false;
    private static synchronized boolean definalize(Field f) {
        if ((f.getModifiers() & Modifier.FINAL) == 0) {
            return true;
        }

        if (MODIFIER_ACCESS == null && !accessAttempted) {
            try {
                Field modifiers = Field.class.getDeclaredField("modifiers");
                modifiers.setAccessible(true);
                MODIFIER_ACCESS = modifiers;
            } catch (NoSuchFieldException e) {
                System.out.println("Could not access Field.modifiers to definalize reflection object. This happens on JVMs > 12, going to see if things work, if not use JVM 8-11");
            }
            accessAttempted = true;
        }
        if (MODIFIER_ACCESS != null) {
            try {
                MODIFIER_ACCESS.setInt(f, f.getModifiers() & ~Modifier.FINAL);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new RuntimeException("Could not definalize field " + f.getDeclaringClass().getName() + "." + f.getName(), e);
            }
            return true;
        }
        return false;
    }

    /**
     * Invokes a method (can be private).
     */
    @SuppressWarnings("unchecked")
    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);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T get(Object target, String name) {
        try {
            int idx = name.lastIndexOf('.');
            if (idx != -1) {
                target = drillField(target, name.substring(0, idx));
                if (target == null) throw new IllegalStateException("Could not find field '" + name + "'");
                name = name.substring(idx + 1);
            }
            Field f = findField(target.getClass(), name);
            if (f == null) throw new IllegalStateException("Could not find '" + name + "'");
            return (T)f.get(target);
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }
    }
}