Adds ability to write key values back to the event from plugins

This commit is contained in:
tastybento 2020-09-13 10:53:35 -07:00
parent c8a85a9ba2
commit a06987ccf4

View File

@ -2,6 +2,7 @@ package world.bentobox.bentobox.api.events;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@ -71,4 +72,26 @@ public abstract class BentoBoxEvent extends Event {
return Collections.emptyMap();
}
}
/**
* Set values back to the event. Use {@link #getKeyValues()} to obtain the map
* @param map - key value map (Name of key, value - object)
* @since 1.15.1
*/
public void setKeyValues(Map<String, Object> map) {
try {
Arrays.stream(Introspector.getBeanInfo(this.getClass(), BentoBoxEvent.class).getPropertyDescriptors())
// only get setters
.filter(pd -> Objects.nonNull(pd.getWriteMethod()))
.forEach(pd -> { // invoke method to set value
if (map.containsKey(pd.getName())) {
try {
pd.getWriteMethod().invoke(this, map.get(pd.getName()));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
});
} catch (IntrospectionException ignore) {}
}
}