Is it possible for the constructor to accept a series of parameters defined by the previous parameter?

Say you have the following class:

public class MyClass { public MyClass() { } } 

I want to be able to pass a certain number of parameters in the constructor, something like this:

  public MyClass(int parameters, int /* "parameters" amount of integers here*/) { } 

I know that I can use the ellipsis operator, but then the constructor will take more or less parameters than int "parameters". Is there any way to do this?

+4
source share
3 answers

You cannot enforce this restriction in the Java compiler, but you can enforce it at runtime by throwing an IllegalArgumentException :

 public MyClass(int numParameters, int... parameters) { if (numParameters != parameters.length) throw new IllegalArgumentException("Number of parameters given doesn't match the expected amount of " + numParameters); // Rest of processing here. } 

This uses the Java varargs function to accept an unknown number of parameters.

Note. I changed the settings a bit for clarity.

+5
source

public MyClass(int parameters, int /* "parameters" amount of integers here*/) { }

See this link for determination methods:

The list of parameters in brackets is a list of inputs with comma-delimited parameters, preceded by their data types, enclosed in parentheses, ()

The parameters do not tell you how much data it expects, it tells you the type .

If you want, you can check the amount inside the constructor at runtime:

if(parametersAmount != desiredAmount) ...

+1
source

I understand that the first argument will be a named constant, and it distinguishes between different cases

 new MyClass(CASE_ONE, p1); 

You can use factory methods

 public static MyClass createCaseOne(int p1){ ... } public static MyClass createCaseTwo(int p1, int p2){ ... } public static MyClass createCaseThree(int p1, int p2, int p3){ ... } ... 
0
source

All Articles