Java SE 7

1. JAVA SE7

2. New Features

SuperPackages

  • 패키지끼리 묶어서 사용할 수 있습니다.
  • 모듈화가 더 편리해질듯 합니다.

superpackage com.foo {
    member package com.foo.api, com.foo.model, com.foo.util
    export com.foo.api;
}

Module System

  • 각 모듈(여기선 클래스 단위를 말하는 것 같습니다.)을 묶어서 사용할 수 있답니다.
  • 멤버를 명시할때 버젼정보도 넣는걸로 보아. 어느정도 버젼에 대한것도 활용 할수 있는것 같습니다.

// MOUDLE_INF/METADATA.module
name=com.wombat.webservice
extensible-metadata=[@Version("1.0")]
members=[com.wombat.webservice.MainApp,
    com.wombat.webservice.PrivateClassA,
    com.wombat.webservice.PrivateInterfaceB]

imports=[ImportModule(org.foo.xml, @VersionConstraint("1.3.0")),
        ImportModule(org.foo.soap, @VersionConstraint("2.0.0+"))]

class-exports=[com.wombat.webservice.MainApp]

다중상속

  • 자바에서 드디어 다중상속을 지원합니다.
  • C++에 비해 가지고 있던 몇가지 단점이 보완된듯합니다.

class NewCollection<class E> extends Collection<E> {
 ...
}

class NewList<class E> extends NewCollection<E>, List<E> {
 ...
}

@NonNull

  • Not null옵션인 듯 합니다. 파라미터 입력시 Null을 입력하지 못하게 하는 것 같습니다.

Map<@NonNull String, @NonEmpty List<@Readonly Document>> files;

  • 저런식으로 타입케스팅되는걸 보면, myObject에 Null값이 있으면 각 타입별 Empty값("")으로 변환해주는 듯 합니다.

myString = (@NonNull String) myObject;


boolean isNonNull = myString intanceof @NonNull String;

@ReadOnly

  • ReadOnly가 Annotiation된 클래스는 @ReadOnly된 변수만 사용가능합니다.

@ReadOnly class RoClass {

    public RoClass() @ReadOnly {} // readonly constructor
    public RoClass(String s) {}   // "mutable" constructor

    String x;          // this-mutable resolves as readonly
    static String sx;  // readonly

    public void testConstructors() {
        RoClass a = new RoClass();   // error
        @ReadOnly RoClass b = new RoClass();
        a = new RoClass("");         // error
        b = new RoClass("");
    }

    public void testFieldsPseudoMutable() {
        @Mutable String a = "a";
        a = x;      // error
        a = sx;     // error
        sx = x;     // error
        x = sx;     // error
    }

    public void testFieldsReadOnly() @ReadOnly {
        @Mutable String a = "a";
        a = x;      // error
        a = sx;     // error
        sx = x;     // error
        x = sx;     // error
    }

}

RoClass.java:12: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:14: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:20: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:21: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:22: a field of a ReadOnly object is not assignable
RoClass.java:23: a field of a ReadOnly object is not assignable
RoClass.java:28: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:29: cannot assign a ReadOnly expression to a Mutable variable
RoClass.java:30: a field of a ReadOnly object is not assignable
RoClass.java:31: a field of a ReadOnly object is not assignable

NIO2

  • NIO는 비동기IO을 추구하지만, 완벽한 비동기IO가 아니기에 Non-Blocking I/O라고 부른답니다.
  • JAVA SE7에서는 asynchoronous I/O를 지원하는 API가 많이 나온답니다.
  • 추가된 java.nio.filesystems 쪽에는 파일 복사를 편하게 할 수있는 PathReference클래스를 제공한답니다.

public class FileCopier {

  public static void main(String[] args) throws IOException {

    if (args.length != 2) {
      System.err.println("Usage: java FileCopier infile outfile");
      return;
    }

    PathReference source = PathReference.from(args[0]);
    PathReference target = PathReference.from(args[1]);

    int flags = CopyFlag.COPY_ATTRIBUTES | CopyFlag.REPLACE_EXISTING;
    source.copyTo(target, flags);

  }
}

  • 이외에 파일권한(file Permissions)이나 속성(Attribute)를 더 편리하게 사용할 수 있답니다.

PathReference ref = PathReference.from("foo.txt");
PosixFileAttributeView view = ref.newFileAttributeView(PosixFileAttributeView.class);
PosixFileAttributes attrs = view.readAttributes();

// prints "-rw-r--r-- alice bandits"
System.out.format("%s\t%s\t%s%n",
        PosixFilePermission.toString(perms), 
        attrs.getOwner(), 
        attrs.getGroup());

// deny others
perms &= ~OTHERS_READ & ~OTHERS_WRITE & ~OTHERS_EXECUTE;
view.updatePermissions(perms);

// change group
UserPrincipal cops = view.lookupPrincipalByGroupName("cops");

view.updateOwners(null, cops);

ParallelArray

  • 가장 기대하고 있는 클래스입니다.
  • 자바에서 드디어 멀티코어CPU에 대한 처리를 제공한답니다.
  • Free로 병렬처리 기술을 사용할수 있답니다.

ParallelArray<Student> students = new ParallelArray<Student>(fjPool, data);
double bestGpa = students.withFilter(isSenior)
                         .withMapping(selectGpa)
                         .max();

public class Student {
    String name;
    int graduationYear;
    double gpa;
}

static final Ops.Predicate<Student> isSenior = new Ops.Predicate<Student>() {
    public boolean op(Student s) {
        return s.graduationYear == Student.THIS_YEAR;
    }
};

static final Ops.ObjectToDouble<Student> selectGpa = new Ops.ObjectToDouble<Student>() {
    public double op(Student student) {
        return student.gpa;
    }
};

BigInteger에 대한 지원

  • 다음과 같은 코드를..

BigInteger low = BigInteger.ONE; 
BigInteger high = BigInteger.ONE; 
for (int i = 0; i < 500; i++) { 
    System.out.print(low); 
    BigInteger temp = high; 
    high = high.add(low); 
    low = temp; 
}; 

  • 다음과 같이 명확히 사용된답니다.

BigInteger low = 1; 
BigInteger high = 1; 
for (int i = 0; i < 500; i++) { 
    System.out.print(low); 
    BigInteger temp = high; 
    high = high + low; 
    low = temp; 
}; 

Syntax

  • 다음과 같은 코드를...

List content = new LinkedList(10); 
content.add(0, "Fred"); 
content.add(1, "Barney"); 
String name = content.get(0); 

  • 이렇게 사용할 수 있답니다.

List content = new LinkedList(10); 
content[0] = "Fred"; 
content[1] = "Barney"; 
String name = content[0]; 

Property

  • getter/setter를 편리하게 사용할수 있습니다.

public class Point {
    property double x;
    property double y;
}

  • 위 클래스를 사용한다면...

Point p = new Point(1, 2);
System.out.println(p.x + " " + p.y);

  • 이렇게 사용한답니다.

Point p = new Point(); 
p.setX(56); 
p.setY(87); 

int z = p.getX(); 

  • 또는 다음과 같이 사용할 수 있답니다.

Point p = new Point();
p->X = 56; // 문법이 C에서 포인터를 사용하는 것 같습니다;
p->y = 87;

int z = p->X;

  • 델파이에서 Property라는 지시자를 사용하면 getter/setter 메소드를 생성해주고,
    사용할 수 있었습니다. 아마 자바에서도 getter/setter에 대한 지원이 아닐까 싶습니다.

DataCoder

  • XML을 편리하게 활용할 클래스랍니다.

package java.xml;

abstract class DataCoder {
    String encode(Object o);
    String encode(Object o, String type);
    <T>T decode(String data, Class<T> c);
    <T>T decode(String data, Class<T> c, String type);
    boolean supports(Class<?> c);
    boolean supports(Class<?> c, String type);

    static final DataCoder JAVA;
    static final DataCoder XSD;
}

  • 예제를 보면 XML 엘리먼트를 객체단위로 다루는 것 같습니다(별다른 인코딩없이)

void addReviewer(XML feature, String reviewer, Timestamp time) {
    DataCoder dc = DataCoder.XSD;
    feature.add(<reviewed>
                    <who>{ reviewer }</who>
                    <when>{ dc.encode(time) }</when>
                </reviewed>);
}

3. 참고 URL

문서에 대하여

  • 최초작성자 : 장선웅
  • 최초작성일 : 2008년 6월 10일
  • 이 문서는 오라클클럽 자바 웹개발자 스터디 모임에서 작성하였습니다.
  • 이 문서를 다른 블로그나 홈페이지에 퍼가실 경우에는 출처를 꼭 밝혀 주시면 고맙겠습니다.~^^