0

我想写一个方法,如果可能的话,它会返回一些 PrimitiveType 的东西,比如 float、integer、boolean 和 String。我想为它使用泛型,但我卡住了,没有找到解决方案。我确实需要它作为 Configparser。我将使用它从 Config 中获取不同的值。

目前它看起来像这样,我知道开关不是这样工作的,但你知道 id 喜欢做什么:

public class ConfigurationManager extends XmlReader {
    private final static String FILE_PATH = "config/config.cfg";
    private static Element xml;

    public ConfigurationManager() throws IOException {
        FileHandle handle = Gdx.files.internal(FILE_PATH);
        this.xml = this.parse(handle);
    }

    public Resolution getResolution() {
        Resolution r = new Resolution();
        r.height = xml.getFloat("height");
        r.width = xml.getFloat("width");
        return r;
    }

    public static <T> T getConfig(Class<T> type, String name) {
        if (type.equals(Integer.class)) {
            return type.cast(xml.getInt(name));
        } else if (type.equals(Float.class)) {
            return type.cast(xml.getFloat(name));
        } else if (type.equals(Boolean.class)) {
            return type.cast(xml.getBoolean(name));
        } else if (type.equals(String.class)) {
            return type.cast(xml.get(name));
        }
        throw new AssertionError("Invalid type");
    }
}

非常感谢

4

2 回答 2

2

好吧,我不认为你可以直接用原始类型来做,但是这样的事情怎么样:

public static <T> T getConfig(Class<T> type, String name) {
   if(type.equals(Integer.class)){
    return type.cast(xml.getInteger(name));
   } else if(type.equals(Float.class)){
    return type.cast(xml.getFloat(name));
   } else if(type.equals(Double.class)) {
    return type.cast(xml.getDouble(name));
   } else if(type.equals(String.class)) {
    return type.cast(xml.getString(name));
   } 
   throw new AssertionError("Invalid type");
}
于 2013-09-28T14:31:10.220 回答
1

您可以使用 Enum 来避免分支逻辑和显式转换。

public enum TypeSelector {
    INTEGER() {
        @Override
        public Integer getValue(Elements xml, String name) {
            return xml.getInteger(name);
        }
    },

    DOUBLE() {
        @Override
        public Double getValue(Elements xml, String name) {
            return xml.getDouble(name);
        }
    };

     private static final Map<Class<?>, TypeSelector> SELECTORS = new HashMap<Class<?>, TypeSelector>() {
            {
                put(Integer.class, INTEGER);
                put(Double.class, DOUBLE);

            }
    };

    public static <T> TypeSelector getSelectorForType(Class<T> c) {
       TypeSelector selector = SELECTORS.get(c);
       if (selector == null) {
          throw new AssertionError("Invalid type");
       }
       return selector;
    }

    public abstract <T> T getValue(Elements xml, String name);
}
于 2013-09-28T19:51:02.570 回答