java泛型T扩展Simpletype?

时间:2013-09-28 14:21:50

标签: java generics

我想编写一个方法,它确实返回一些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");
    }
}

非常感谢

2 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分: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);
}