Varargs : 가변 인자

2022. 1. 21. 01:07CSE/JAVA

공식 문서 : https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html

 

Varargs

Varargs In past releases, a method that took an arbitrary number of values required you to create an array and put the values into the array prior to invoking the method. For example, here is how one used the MessageFormat class to format a message: Object

docs.oracle.com

 

스프링 강의를 듣다가 Object... objects 이런 부분이 나와서 Varargs에 대해 알아보았다.

다음은 공식 문서를 간단히 해석해놓은 부분이다.

 

Varargs가 사용되기 전에는, 메소드에 임의적인 개수의 파라미터를 넣기 위해서는 다음과 같이 배열을 사용해야 했다.

Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", arguments);

 

Varargs도 실제로는 여러개의 arguments들을 배열로 넘겨주는 것이 맞지만, 이를 알아서 자동적으로 처리해준다.

또한, 이미 존재하고 있는 API들에도 적용되어있다.

즉, 위에서 사용한 MessageFormat.format()함수는 현재 다음과 같다.

public static String format(String pattern, Object... arguments);

따라서, 위의 코드를 다음과 같이 간단하게 사용할 수 있게 되었다.

String result = MessageFormat.format(
    "At {1,time} on {1,date}, there was {2} on planet "
    + "{0,number,integer}.",
    7, new Date(), "a disturbance in the Force");