2010년 7월 12일 월요일

Wrapper 클래스의 getBoolean, getInteger, getLong 메서드

Wrapper 클래스 중에서 Boolean, Integer, Long 클래스에는 다른 래퍼 클래스에 없는 get 메서드가 구현되어 있다.

보통 문자열로 래퍼 클래스를 생성하는 경우에는 각 래퍼 클래스의 스태틱 메서드로 parse 메서드가 구현되어 있다.

  • Boolean.parseBoolean(String value)

  • Byte.parseByte(String value)

  • Short.parseShort(String value)

  • Integer.parserInt(String value)

  • Long.parseLong(String value)

  • ... etc.


parse메서드는 입력되는 문자열 값으로 래퍼 클래스를 생성하는 용도로 사용된다.

그러나 Boolean, Integer, Long 클래스는 parse 메서드와는 별도로 get 메서드가 구현되어 있다.

  • Boolean.getBoolean(String name)

  • Integer.getInteger(String name)

  • Long.getLong(String name)



get메서드는 System.getProperties()에 설정된 값에서 각각 boolean, int, long값을 가져오는 기능을 한다. getBoolean의 경우에 대소문자 구분없이 "TRUE"로 값이 설정되면 true를 리턴하고, 값이 설정되지 않았다거나, "TRUE"이외의 값으로 설정된 경우에는 false를 리턴한다.
getInteger와 getLong의 경우에는 값이 integer 값이나 long 값으로 설정되어 있는 경우에 값을 리턴하고, 값이 설정되지 않았다거나 int 또는 long 타입이 아닌 문자열로 설정된 경우에는 null을 리턴한다.
long값의 경우 10L과 같이 지정되는 경우에도 null을 리턴한다.
실제로 많이 사용될거라 예상되지는 않지만 parse메서드와 혼동하지 않았으면 하는 마음으로 포스트를 등록한다.

아래 예제 코드는 get 메서드 사용 예제다.

@Test
public void testBoolean() throws Exception {
System.out.println(Boolean.getBoolean("true"));
System.out.println(Boolean.getBoolean("True"));
System.out.println(Boolean.getBoolean("TRUE"));
System.out.println(Boolean.getBoolean("tRuE"));

// 이건 새롭네..
// Boolean.getBoolean()은 시스템 프로퍼티에 설정된 값이 대소문자에 상관없이 'true'인 경우에
// true를 리턴한다.
System.setProperty("tempKey", "True");
System.out.println(Boolean.getBoolean("tempKey"));

System.setProperty("sampleIntValue", "19");
System.out.println(Integer.getInteger("sampleIntValue"));

System.setProperty("sampleLongValue", "10");
System.out.println(Long.getLong("sampleLongValue"));

}



false
false
false
false
true
19
10

댓글 없음:

댓글 쓰기