Chapter 6. Varargs
Prev |  | Next

## Chapter 6. Varargs

## Variable-length Argument Lists in Java 5

Java 5 (and hence AspectJ 5) allows you to specify methods that take a variable number of arguments of a specified type. This is achieved using an ellipsis (...) in the method signature as shown:

    		public void foo(int i, String... strings) {
    		}

A method or constructor may take at most one variable length argument, and this must always be the last declared argument in the signature.

### Calling Methods and Constructors with variable-length arguments

A varargs method may be called with zero or more arguments in the variable argument position. For example, given the definition of `foo` above, the following calls are all legal:

        	foo(5);
        	foo(5,"One String");
        	foo(7,"One String","Two Strings");
        	foo(3,"One String","Two Strings","Three Strings");

A varargs parameter is treated as an array within the defining member. So in the body of `foo` we could write for example:

        	public void foo(int i, String... strings) {
        	  String[] someStrings = strings;
        	  // rest of method body
        	}

One consequence of this treatment of a varargs parameter as an array is that you can also call a varargs method with an array:

        	foo(7,new String[] {"One String","Two Strings"});

Prev | Home | Next
Covariant methods and Join Point matching | Up | Using Variable-length arguments in advice and pointcut expressions