gpt4 book ai didi

java - 根据条件调用特定方法

转载 作者:行者123 更新时间:2023-11-30 07:57:03 25 4
gpt4 key购买 nike

我最近写了这段代码:

  public Object getProperty(String key) {
if (this.plugin.getConfig().isBoolean(key)) {
return this.plugin.getConfig().getBoolean(key);
} else if (this.plugin.getConfig().isColor(key)) {
return this.plugin.getConfig().getColor(key);
} else if (this.plugin.getConfig().isConfigurationSection(key)) {
return this.plugin.getConfig().getConfigurationSection(key);
} else if (this.plugin.getConfig().isDouble(key)) {
return this.plugin.getConfig().getDouble(key);
} else if (this.plugin.getConfig().isInt(key)) {
return this.plugin.getConfig().getInt(key);
} else if (this.plugin.getConfig().isItemStack(key)) {
return this.plugin.getConfig().getItemStack(key);
} else if (this.plugin.getConfig().isList(key)) {
return this.plugin.getConfig().getList(key);
} else if (this.plugin.getConfig().isLong(key)) {
return this.plugin.getConfig().getLong(key);
} else if (this.plugin.getConfig().isOfflinePlayer(key)) {
return this.plugin.getConfig().getOfflinePlayer(key);
} else if (this.plugin.getConfig().isPrimitiveWrapper(key)) {
return this.plugin.getConfig().getPrimitiveWrapper(key);
} else if (this.plugin.getConfig().isSet(key)) {
return this.plugin.getConfig().getSet(key);
} else if (this.plugin.getConfig().isString(key)) {
return this.plugin.getConfig().getString(key);
} else if (this.plugin.getConfig().isVector(key)) {
return this.plugin.getConfig().getVector(key);
}
}

如您所见,它 super 重复且非常丑陋。

有没有更好的写法?


plugin.getConfig() 返回 one of these .我想创建一个方法,当给定指向 YAML 文件中某个值的路径 (key) 时,无论其类型是什么,我都可以返回该值。

最佳答案

你为什么不简单地写下这个,而不是所有这些胡言乱语:

public Object getProperty(String key) {
return this.plugin.getConfig().get(key);
}

这尤其是因为您最终只返回一个对象。所以最好返回您从 YAML 中获得的内容。

如果您确实想让客户的生活变得轻松,请尝试单独公开ConfigurationSection 的方法,而不是组合使用它们。

此处的标准做法取决于此代码的客户端类型。如果客户端将通过将它们转换为实际类来直接使用各种类型的属性,那么您可以从 ConfigurationSection 中公开不同的方法。但是,如果直接客户端只是将属性传递给其他类,那么最好只公开单个方法

关于java - 根据条件调用特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41602973/

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