简体   繁体   English

在Java中调用方法之前检查参数数量

[英]checking the number of arguments before calling the method in Java

In my program, I have a method which is below; 在我的程序中,有一个下面的方法;

private void foo(String title, String[] subtitles, int ... subtitleValues)

My requirement is ; 我的要求是;

  • number of subtitles and subtitleValues must be equal. 字幕数和subtitleValues必须相等。 User can send any number of subtitles and subtitle values but as I said equal number of subtitles and subtitleValues. 用户可以发送任意数量的字幕和字幕值,但是正如我所说的,字幕和subtitleValues的数量相同。

I don't want to take both arguments and check their counts in foo function and say your table can not be created because of unequal subtitles and subtitleValues. 我不想同时使用两个参数并在foo函数中检查它们的计数,并说由于字幕和subtitleValues值不相等而无法创建您的表。 What I want is; 我想要的是 prevent user to send unequal arguments. 防止用户发送不相等的参数。 How can I do that? 我怎样才能做到这一点?

Thanks in advance 提前致谢

PS : I didn't find a proper title, so if you have, please feel free to change it. PS:我找不到合适的标题,所以,如果有,请随时更改。

You can't do it like this. 你不能这样做。 What you can do to make your method harder to call wrongly is to use a fluent API for a builder like this: 要使您的方法更难于被错误调用,您可以做的就是为这样的构建器使用流畅的API:

class FooBuilder {
  public static FooBuilder withTitle(String title);
  public FooBuilder withSubtitle(String subtitle, int subtitleValue);
  public Foo build();
}

I left out the implementation for brevity. 为了简洁起见,我省略了该实现。 Then you can call it like this: 然后您可以这样称呼它:

Foo foo = FooBuilder.withTitle("MyTitle").withSubtitle("st1", 1).withSubtitle("st2", 2).build();

Create a class containing a subtitle, subtitleValue pair. 创建一个包含字幕subtitleValue对的类。 Have your method accept a vararg (or list, or array) of instances of this class. 让您的方法接受此类实例的vararg(或列表或数组)。

In this case you should create probably separate class Subtitle which represents subtitles. 在这种情况下,您应该创建可能单独的代表字幕的类Subtitle And create appropriate constructor or method for adding subtitles one by one. 并创建适当的构造函数或方法以一对一地添加字幕。

Then rephrase your foo method as: 然后将您的foo方法改写为:

private void foo(String title, List<Subtitle> subtitles)

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

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