java5, java6 的新特性

下面简单的列出Java5和Java6的主要新特性。

Java5:

1。泛型 Generics :

引入泛型之后,允许指定集合里元素的类型,面去了强制类型转换,并得到强类型在编译时刻进行类型检查的好处。

不光是类型安全,Parameterized Type作为参数和返回值,Generic是vararg、annotation、enumeration、collection等功能的基石

a, 类型安全

抛弃List、Map,使用List<String>、Map<Integer, String>

给List、Map添加元素或者使用Iterator<T>遍历时,编译期就可以给你检查出类型错误

b, 方法参数和返回值统统加上Type

抛弃List getStringListFromIntegerList(List list)

使用List<String> getgetStringListFromIntegerList(List<Integer> list)

c, 不再需要类型转换

List<String> l = new ArrayList<String>()

String s = l.get(i)

d, 类型通配符

假设一个打印List<T>中元素的方法printList,我们希望任何类型T的List<T>都可以被打印:

代码

1. public void printList(List<?> list, PrintStream out) throws IOException {

2. for (Iterator<?> i = list.iterator(); i.hasNext(); ) {

3. out.println(i.next().toString());

4. }

5. }

类型通配符"?"让我们的printList方法更通用

e, 限制类型参数

如果通配符?让我们的参数类型过于广泛,我们还可以限制一下它:

代码

1. public void printList(List<? extends Number> list, PrintStream out) throws IOException {

2. for (Iterator<? extends Number> i = list.iterator(); i.hasNext(); ) {

3. out.println(i.next().toString());

4. }

5. }

2。枚举类型 Enumeration:

3。自动类型包装和解包装(autoboxing & unboxing):

听起来很玄,实际上做的事情非常简单,类型自动转换罢了。

自动装包:基本类型自动转为包装类.(int >> Integer)

自动拆包:包装类自动转为基本类型.(Integer >> int)

Java 1.4

public class program {

public static void main(String[] args) {

int i = 13;

Integer o = new Integer(i);

Integer x = new Integer(13);

int y = x.intValue();

}

}

Java 5

public class program {

public static void main(String[] args) {

// Boxing

int i = 13;

Integer o = i;

// UnBoxing

Integer x = new Integer(13);

int y = x;

}

}

4。变长参数 varargs ( variable number of arguments)

参数类型相同时,把重载函数合并到一起了

以前是这样:

public void write(Object obj1)

public void write(Object obj1,Object obj2)

public void write(Object Obj1,Object obj2,Object obj3)

现在合在一起只要这样写就行了:  

public void write(Object... objs) {

for (Object obj: objs)

System.out.println(obj);

}

5。Annotations

Annotation是Java中的metadata

A, Tiger中预定义的三种标准annotation

a, Override

指出某个method覆盖了superclass的method

当你要覆盖的方法名拼写出错时编译不通过

b, Deprecated

指出某个method或element类型的使用是被阻止的

子类将不能覆盖该方法

c, SupressWarnings

关闭class、method、field/variable初始化的编译期警告

比如没有List没有使用Generic,则@SuppressWarnings("unchecked")将去掉编译期警告,这对将程序移植到JDK1.4有意义

B, 自定义annotation

public @interface Marked {}

C, meta-annotation

或者说annotation的annotation

四种标准的meta-annotation全部定义在java.lang.annotaion包中:

a, Target

指定所定义的annotation可以用在哪些程序单元上

如果Target没有指定,则表示该annotation可以使用在任意程序单元上

代码

1. @Target({ElementType.ANNOTATION_TYPE,

2. ElementType.CONSTRUCTOR,

3. ElementType.FIELD,

4. ElementType.LOCAL_VARIABLE,

5. ElementType.METHOD,

6. ElementType.PACKAGE,

7. ElementType.PARAMETER,

8. ElementType.TYPE})

9. public @interface TODO {}

b, Retention

指出Java编译期如何对待annotation

annotation可以被编译期丢掉,或者保留在编译过的class文件中

在annotation被保留时,它也指定是否会在JVM加载class时读取该annotation

代码

1. @Retention(RetentionPolicy.SOURCE) // Annotation会被编译期丢弃

2. public @interface TODO1 {}

3. @Retention(RetentionPolicy.CLASS) // Annotation保留在class文件中,但会被JVM忽略

4. public @interface TODO2 {}

5. @Retention(RetentionPolicy.RUNTIME) // Annotation保留在class文件中且会被JVM读取

6. public @interface TODO3 {}

c, Documented

指出被定义的annotation被视为所熟悉的程序单元的公开API之一

被@Documented标注的annotation会在javadoc中显示,这在annotation对它标注的元素被客户端使用时有影响时起作用

d, Inherited

该meta-annotation应用于目标为class的annotation类型上,被此annotattion标注的class会自动继承父类的annotation

D, Annotation的反射

我们发现java.lang.Class有许多与Annotation的反射相关的方法,如getAnnotations、isAnnotationpresent

我们可以利用Annotation反射来做许多事情,比如自定义Annotation来做Model对象验证

代码

1. @Retention(RetentionPolicy.RUNTIME)

2. @Target({ ElementType.FIELD, ElementType.METHOD })

3. public @interface RejectEmpty {

4. /** hint title used in error message */

5. String value() default "";

6. }

7.

8. @Retention(RetentionPolicy.RUNTIME)

9. @Target( { ElementType.FIELD, ElementType.METHOD })

10. public @interface AcceptInt {

11. int min() default Integer.MIN_VALUE;

12. int max() default Integer.MAX_VALUE;

13. String hint() default "";

14. }

使用@RejectEmpty和@AcceptInt标注我们的Model的field,然后利用反射来做Model验证

6。新的迭代语句 (enhanced for loop) for/in

抛弃Iterator吧

代码

  1. for(int n : numbes) {
  2. println(n);
  3. }
  4. for(String s : stringList) {
  5. println(s);
  6. }
自定义实现Iterable接口或继承现有Collection的类来让你的类可以使用for/in

7。静态引入 static imports

就是把其它类的静态方法引入,变成自己的方法。

import static java.lang.Math.*;

r = sin(PI * 2); 

//无需再写r = Math.sin(Math.PI * 2);

enum元素也可以import

  1. import static java.lang.System.out;
  2. import static xx.xx.xx.SomeEnum.*;
8。新的格式化方法 java.util.Formatter

让你拥有C的printf()风格的字符串格式化

formatter.format("Remaining account balance: $%.2f", balance);

9。新的线程模型和并发库 Thread framework

Tiger引进大量全新的并发性功能,更好的支持mutilthread

HashMap的替代者ConcurrentHashMap和ArrayList的替代者CopyOnWriteArrayList让我们用的放心、舒心、省心

在大并发量读取时采用java.util.concurrent包里的一些类会让大家满意

BlockingQueue、Callable、Executor、Semaphore...

Java6:

1。引入了一个支持脚本引擎的新框架

2。UI的增强

3。对Web Service支持的增强(JAX-WS 2.0 和 JAXB 2.0)

4。一系列新的安全相关的增强(本地敏感资源服务 Locale Sensitive Services SPI)

5。JDBC 4.0

6。Compiler API

7。通用的Annotations支持