Wednesday, 3 February 2021

Spring Shell: Parameter Arity

Sometimes there are situations, where you may need to take multiple values to a parameter. You can do this using ‘arity’ attribute of @ShellOption annotation.

 

Example

@ShellComponent(value = "Multi Valued Parameters Demo")
public class MultiValuedParametersDemo {

	@ShellMethod(value = "Commands to Calculate Square of given numbers", key = "square", prefix = "-")
	public String SquarelOfNumbers(@ShellOption(arity=5)int[] input, String message) {

		StringBuilder builder = new StringBuilder();

		for (int i : input) {
			int result = i * i;
				
			builder.append(String.format(message, i, result)).append("\n");
		}

		return builder.toString();
	}
}

 

In the above snippet, I mentioned arity as 5 for the argument input[]. So I can call the command ‘square’ like below.

 

square -input 1 2 3 4 5 -message "Square of a number %d is %d"

shell:>square -input 1 2 3 4 5 -message "Square of a number %d is %d"
Square of a number 1 is 1
Square of a number 2 is 4
Square of a number 3 is 9
Square of a number 4 is 16
Square of a number 5 is 25

You can download complete application from this link.

https://github.com/harikrishna553/springboot/tree/master/shell/hello-world

 

Note:

Infinite Arity yet to be implemented.

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment