Declaring references to methods/fields in extension values does not work correctly but errors instead #13

Closed
opened 2024-08-04 16:54:15 -04:00 by owlsys · 0 comments
Owner

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);
}
}

see https://git.frogmc.dev/frogmc/FrogLoader/src/commit/a4ab17f5a8cf40ca88c79ee6b6e708ffcbc58974/src/main/java/dev/frogmc/frogloader/api/mod/ModExtensions.java#L83-L127
Sign in to join this conversation.
No labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference: frogmc/FrogLoader#13
No description provided.