Declaring references to methods/fields in extension values does not work correctly but errors instead #13
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
see
/**
* Run the given action on this extension if it is present.
* <p>This method simplifies handling references to classes or methods.</p>
* It will first query the string value of the extension and, if it is found, create a new instance of the referenced class
* or invoke the referenced method to retrieve an instance of the provided class. Then the provided action is run on this
* object.
*
* @param key The name of the extension
* @param type The class type of the extension (The class the extension class is extending/implementing)
* @param action The action to run on the newly retrieved instance of the provided class
* @param <T> The type of the class
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public <T> void runIfPresent(String key, Class<T> type, Consumer<T> action) {
Object value = get(key);
if (value == null) {
return;
}
Consumer<String> c = s -> {
try {
MethodHandle handle;
if (s.contains("::")) {
String[] parts = s.split("::");
handle = MethodHandles.lookup().findVirtual(Class.forName(parts[0]), parts[1], MethodType.methodType(type));
} else {
handle = MethodHandles.lookup().findConstructor(Class.forName(s), MethodType.methodType(void.class));
}
T object = (T) handle.invoke();
if (object != null) {
action.accept(object);
}
} catch (Throwable e) {
LOGGER.warn("Failed to instantiate Extension: ", e);
}
};
if (value instanceof String s) {
c.accept(s);
} else if (value instanceof Collection l) {
((Collection<String>) l).forEach(c);
}
}