001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.actions;
003
004/**
005 * Abstract class for <i>key=value</i> parameters, used in {@link ParameterizedAction}.
006 * <p>
007 * The key ({@link #name}) is a string and the value of class {@code T}. The value can be
008 * converted to and from a string.
009 * @param <T> the value type
010 */
011public abstract class ActionParameter<T> {
012
013    private final String name;
014
015    /**
016     * Constructs a new ActionParameter.
017     * @param name parameter name (the key)
018     */
019    protected ActionParameter(String name) {
020        this.name = name;
021    }
022
023    /**
024     * Get the name of this action parameter.
025     * The name is used as a key, to look up values for the parameter.
026     * @return the name of this action parameter
027     */
028    public String getName() {
029        return name;
030    }
031
032    /**
033     * Get the value type of this action parameter.
034     * @return the value type of this action parameter
035     */
036    public abstract Class<T> getType();
037
038    /**
039     * Convert a given value into a string (serialization).
040     * @param value the value
041     * @return a string representation of the value
042     */
043    public abstract String writeToString(T value);
044
045    /**
046     * Create a value from the given string representation (deserialization).
047     * @param s the string representation of the value
048     * @return the corresponding value object
049     */
050    public abstract T readFromString(String s);
051
052    /**
053     * Simple ActionParameter implementation for string values.
054     */
055    public static class StringActionParameter extends ActionParameter<String> {
056
057        /**
058         * Constructs a new {@code StringActionParameter}.
059         * @param name parameter name (the key)
060         */
061        public StringActionParameter(String name) {
062            super(name);
063        }
064
065        @Override
066        public Class<String> getType() {
067            return String.class;
068        }
069
070        @Override
071        public String readFromString(String s) {
072            return s;
073        }
074
075        @Override
076        public String writeToString(String value) {
077            return value;
078        }
079    }
080}