繁体   English   中英

一种聪明的方法来接受唯一对象的任意组合作为参数?

[英]Clever way for a method to accept any combination of unique objects as parameters?

我有一个可以用StringRecordCriteria构造的类。 有什么方法允许方法签名以任何顺序接受这些参数(除了创建多个构造函数之外)? 这比什么都更是一个学术问题。

不, 语言规范没有提到这种简单的方法。

您总是可以自己传递Object并自己执行类型检查,但这是错误的方法。

Java 不允许使用命名参数(在链接中绕着它)

一种选择是创建一个保存并表示这三个参数的类,但是我只建议如果这三个参数以某种方式相关联,从而在对象模型中具有逻辑意义。

您可以执行以下操作:

public class MyClass ()
{

  private String _str;
  private Record _rec;
  private Criteria _crit;

  public MyClass ()
  {
    _rec = null;
    _crit = null;
    _str = null;
  }

  public MyClass string (String str)
  {
    this._str = str;
    return this;
  }

  public MyClass record (Record rec)
  {
    this._rec = rec;
    return this;
  }

  public MyClass criteria (Criteria crit)
  {
    this._crit = crit;
    return this;
  }

  public static void getInstance ()
  {
    return new MyClass ();
  }

  public static void main (String[] args)
  {
     MyClass instance = MyClass.getInstance ().string("something").criteria(someCriteria).record(someRecord);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM