diff --git a/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java b/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java index 60634835..df72b0c2 100644 --- a/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java +++ b/cloud-core/src/main/java/cloud/commandframework/context/CommandContext.java @@ -115,6 +115,24 @@ public final class CommandContext { } } + /** + * Get a value from its key. Will return {@link Optional#empty()} + * if no value is stored with the given key + * + * @param argument Argument + * @param Value type + * @return Value + */ + public @NonNull Optional getOptional(final @NonNull CommandArgument argument) { + final Object value = this.internalStorage.get(argument.getName()); + if (value != null) { + @SuppressWarnings("ALL") final T castedValue = (T) value; + return Optional.of(castedValue); + } else { + return Optional.empty(); + } + } + /** * Remove a stored value from the context * @@ -142,6 +160,32 @@ public final class CommandContext { return (T) value; } + /** + * Get a required argument from the context. This will thrown an exception + * if there's no value associated with the given argument + * + * @param argument The argument + * @param Argument type + * @return Stored value + * @throws NullPointerException If no such value is stored + */ + public @NonNull T get(final @NonNull CommandArgument argument) { + return this.get(argument.getName()); + } + + /** + * Get a value if it exists, else return the provided default value + * + * @param argument Argument + * @param defaultValue Default value + * @param Argument type + * @return Stored value, or supplied default value + */ + public @Nullable T getOrDefault(final @NonNull CommandArgument argument, + final @Nullable T defaultValue) { + return this.getOptional(argument.getName()).orElse(defaultValue); + } + /** * Get a value if it exists, else return the provided default value * @@ -246,7 +290,7 @@ public final class CommandContext { /** * Set the end time * - * @param end End time (in nanoseconds) + * @param end End time (in nanoseconds) * @param success Whether or not the argument was parsed successfully */ public void setEnd(final long end, final boolean success) {