본문 바로가기

개발

java7 특징 및 예제

1. Performing a switch statement on a string
 - Switch문 내에서 문자열 사용 가능

public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;

         default:
 throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;

}


특징 : 대소문자를 구분한다.


Deprecate @ExpectedException

Background

  • @ExpectedException was introduced in Spring 2.0 in order to allow developers to declare an expected exception via an annotation when using JUnit 3.8.2.
  • JUnit 4+ supports expected exceptions out of the box via the expected attribute of the JUnit @Test annotation.
  • All JUnit 3.8.x support was deprecated in Spring 3.1 M2.
  • SpringJUnit4ClassRunner treats expected exceptions configured via Spring's @ExpectedException annotation and JUnit's @Test annotation identically.
  • Consequently, Spring's @ExpectedException annotation no longer provides added value in a JUnit 4+ world.


테스트를 하려던 도중 exception을 내려는 테스트 코드를 작성하는 
@ExpectedException이 deprecate되서 찾아보니 스프링 2.0, junit 3.8.2를 사용할때 
제공 했는데 junit4 에서  @test 어노테이션에 expected를 제공하는것으로 인해 deprecate 됨. 그래서 다음과 같이 테스트 하니 잘 동작함. 









2. Catching multiple exceptions

catch에서 여러개의 exception 캐치가 가능해짐. 


<JDK 7 이전>
try {
    Path fp = path.toRealPath(true);
} catch (NoSuchFileException x) {
    System.err.format("%s: no such file or directory%n", path);
    ...
} catch (IOException x) {
    System.err.format("%s%n", x);
    ...
}


<JDK 7>

try {
    Path fp = path.toRealPath(true);
} catch (NoSuchFileException | IOException x) {
    System.err.format("%s: no such file or directory%n", path);
    ...
}




3. The try-with-resources Statement

jdk 7에서 AutoCloseable and Closeable interfaces가 추가 되었는데 

이를 구현한 클래스 에서는 별도로 close를 호출 할 필요가 없음. 


<이전>
static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
    return br.readLine();
  } finally {
    if (br != null) br.close();
  }
}

<이후>
public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.Charset.forName("US-ASCII");
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with try-with-resources statement

    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    )
 {

      // Enumerate each entry

      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
  }







4. G1 Garbage Collector

The Garbage-First (G1) garbage collector is fully supported in Oracle JDK 7 update 4 and later releases. The G1 collector is a server-style garbage collector, targeted for multi-processor machines with large memories.

  • More than 50% of the Java heap is occupied with live data.
  • The rate of object allocation rate or promotion varies significantly.
  • Undesired long garbage collection or compaction pauses (longer than 0.5 to 1 second)