简体   繁体   中英

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

I have a class that can be constructed with a String , Record , and Criteria . Is there any way to allow the method signature to accept these parameters in any order (other than creating multiple constructors)? This is more of an academic question than anything.

No, the language specification mentions no such easy way.

You can always pass Object s and perform type checks yourself, but that's a wrong approach.

Java does not allow named parameters (ways around it in link) .

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

You can do something like this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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