gpt4 book ai didi

java 泛型 T 扩展 Simpletype?

转载 作者:行者123 更新时间:2023-12-01 23:32:59 27 4
gpt4 key购买 nike

我想编写一个方法,它确实返回 PrimitiveType 的某些内容,例如 float 、整数、 boolean 值,如果可能的话还返回字符串。我想使用泛型,但我卡住了,没有找到解决方案。我确实需要它作为 Configparser。我将使用它从配置中获取不同的值。

目前它看起来像这样,我知道开关不能像这样工作,但你知道 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");
}
}

非常感谢

最佳答案

嗯,我不认为你可以直接使用原始类型来做到这一点,但是像这样的东西怎么样:

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");
}

关于java 泛型 T 扩展 Simpletype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19067950/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com