1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import java.lang.reflect.AccessibleObject;
|
---|
5 | import java.security.AccessController;
|
---|
6 | import java.security.PrivilegedAction;
|
---|
7 | import java.util.Collection;
|
---|
8 | import java.util.function.Function;
|
---|
9 |
|
---|
10 | /**
|
---|
11 | * Reflection utilities.
|
---|
12 | * @since 14977
|
---|
13 | */
|
---|
14 | public final class ReflectionUtils {
|
---|
15 |
|
---|
16 | private ReflectionUtils() {
|
---|
17 | // Hide default constructor for utils classes
|
---|
18 | }
|
---|
19 |
|
---|
20 | /**
|
---|
21 | * Sets {@code AccessibleObject}(s) accessible.
|
---|
22 | * @param objects objects
|
---|
23 | * @see AccessibleObject#setAccessible
|
---|
24 | */
|
---|
25 | public static void setObjectsAccessible(final AccessibleObject... objects) {
|
---|
26 | if (objects != null && objects.length > 0) {
|
---|
27 | AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
|
---|
28 | for (AccessibleObject o : objects) {
|
---|
29 | if (o != null) {
|
---|
30 | o.setAccessible(true);
|
---|
31 | }
|
---|
32 | }
|
---|
33 | return null;
|
---|
34 | });
|
---|
35 | }
|
---|
36 | }
|
---|
37 |
|
---|
38 | /**
|
---|
39 | * To use from a method to know which class called it.
|
---|
40 | * @param exclusions classes to exclude from the search. Can be null
|
---|
41 | * @return the first calling class not present in {@code exclusions}
|
---|
42 | */
|
---|
43 | public static Class<?> findCallerClass(Collection<Class<?>> exclusions) {
|
---|
44 | return findCaller(x -> {
|
---|
45 | try {
|
---|
46 | return Class.forName(x.getClassName());
|
---|
47 | } catch (ClassNotFoundException e) {
|
---|
48 | Logging.error(e);
|
---|
49 | return null;
|
---|
50 | }
|
---|
51 | }, exclusions);
|
---|
52 | }
|
---|
53 |
|
---|
54 | private static <T extends Object> T findCaller(Function<StackTraceElement, T> getter, Collection<T> exclusions) {
|
---|
55 | StackTraceElement[] stack = Thread.currentThread().getStackTrace();
|
---|
56 | for (int i = 3; i < stack.length; i++) {
|
---|
57 | T t = getter.apply(stack[i]);
|
---|
58 | if (exclusions == null || !exclusions.contains(t)) {
|
---|
59 | return t;
|
---|
60 | }
|
---|
61 | }
|
---|
62 | return null;
|
---|
63 | }
|
---|
64 | }
|
---|