根据条件调用某种方法

时间:2017-01-12 00:02:43

标签: java repeat

我最近写了这段代码:

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

正如你所看到的,它是超级重复且非常难看。

有没有更好的方法可以写出来?

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

1 个答案:

答案 0 :(得分:3)

而不是所有这些笨蛋,为什么不简单地写下这个:

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

这尤其是因为你最终只返回Object。所以最好还是从YAML那里得到的。

如果您确实希望让客户的生活更轻松,请尝试单独展示ConfigurationSection的方法,而不是将它们合并。

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