source: josm/trunk/src/org/openstreetmap/josm/tools/ReflectionUtils.java@ 15547

Last change on this file since 15547 was 14978, checked in by Don-vip, 5 years ago

fix #17574 - fix IAE when plugins modify preferences (regression from r14977)

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