jdk1.5新特性

“JDK1.5”(开发代号猛虎)的一个重要主题就是通过新增一些特性来简化开发,这些特性包括泛型,for-each 循环,自动装包/拆包,枚举,可变参数, 静态导入。使用这些特性有助于我们编写更加清晰,精悍,安全的代码。

 

下面我们简单介绍一下这些新特性。

 

 

1、泛型:泛型、通配符、有限制通配符、泛型方法

 

2、加强循环

 

3、 自动装箱/拆箱

 

4、枚举

 

5、可变参数

 

6、静态引入

 

7、元数据

 

8、 控制台输入

 

9、改变返回类型

 

10、格式化I/O1.泛型(Generic)

 

 

 

1.泛型

C++通过模板技术可以指定集合的元素类型,而Java在1.5之前一直没有相对应的功能。一个集合可以放任何类型的对象,相应地从集合里面拿对象的时候我们也不得不对他们进行强制得类型转换。猛虎引入了泛型,它允许指定集合里元素的类型,这样你可以得到强类型在编译时刻进行类型检查的好处。

Collection<String> c = new ArrayList();

c.add(new Date());

编译器会给出一个错误,

add(java.lang.String) injava.util.Collection<java.lang.String> cannot be applied to(java.util.Date)

 

 

2.For-Each循环

For-Each循环得加入简化了集合的遍历。假设我们要遍历一个集合对其中的元素进行一些处理。典型的代码为:

void processAll(Collection c){

for(Iterator i=c.iterator(); i.hasNext(){

MyClass myObject = (MyClass)i.next();

myObject.process();

}

}

使用For-Each循环,我们可以把代码改写成,

void processAll(Collection<MyClass>c){

for (MyClass myObject :c)

myObject.process();

}

这段代码要比上面清晰许多,并且避免了强制类型转换。

 

 

3.自动装包/拆包(Autoboxing/unboxing)

自动装包/拆包大大方便了基本类型数据和它们包装类地使用。

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

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

在JDK1.5之前,我们总是对集合不能存放基本类型而耿耿于怀,现在自动转换机制解决了我们的问题。

int a = 3;

Collection c = new ArrayList();

c.add(a);//自动转换成Integer.

 

Integer b = new Integer(2);

c.add(b + 2);

这里Integer先自动转换为int进行加法运算,然后int再次转换为Integer.

 

 

4.枚举(Enums)

JDK1.5加入了一个全新类型的“类”-枚举类型。为此JDK1.5引入了一个新关键字enmu.我们可以这样来定义一个枚举类型。

 

public enum Color

{

Red,

White,

Blue

}

然后可以这样来使用Color myColor = Color.Red.

枚举类型还提供了两个有用的静态方法values()和valueOf(). 我们可以很方便地使用它们,例如

for (Color c : Color.values())

System.out.println(c);

 

5.可变参数(Varargs)

可变参数使程序员可以声明一个接受可变数目参数的方法。注意,可变参数必须是函数声明中的最后一个参数。假设我们要写一个简单的方法打印一些对象,

util.write(obj1);

util.write(obj1,obj2);

util.write(obj1,obj2,obj3);

在JDK1.5之前,我们可以用重载来实现,但是这样就需要写很多的重载函数,显得不是很有效。如果使用可变参数的话我们只需要一个函数就行了。一个方法只能定义一个可变参数

 

//取值方法

public void write(Object... objs) {

for (Object obj: objs)

System.out.println(obj);

}

 

// 取值方法定义一个list变量variabledeclaration

 

 

 

private list features;

 

 

 

// assignment in method or constructor body

 

 

 

this.features =java.util.arrays.aslist(objs);

 

 

在引入可变参数以后,Java的反射包也更加方便使用了。对于c.getMethod("test", new Object[0]).invoke(c.newInstance(),new Object[0])),

现在我们可以这样写了c.getMethod("test").invoke(c.newInstance()),这样的代码比原来清楚了很多。

 

 

6.静态导入(Static Imports)

要使用用静态成员(方法和变量)我们必须给出提供这个方法的类。使用静态导入可以使被导入类的所有静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。

import static java.lang.Math.*;

…….

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

 

The For-Each Loop Language Contents

 

 

--------------------------------------------------------------------------------

Iterating over a collection is uglier thanit needs to be. Consider the following method, which takes a collection oftimer tasks and cancels them:

void cancelAll(Collection<TimerTask>c) {

for (Iterator<TimerTask> i =c.iterator(); i.hasNext(); )

i.next().cancel();

}

 

The iterator is just clutter. Furthermore,it is an opportunity for error. The iterator variable occurs three times ineach loop: that is two chances to get it wrong. The for-each construct gets ridof the clutter and the opportunity for error. Here is how the example lookswith the for-each construct:

 

void cancelAll(Collection<TimerTask>c) {

for (TimerTask t : c)

t.cancel();

}

 

When you see the colon (:) read it as “in.”The loop above reads as “for each TimerTask t in c.” As you can see, thefor-each construct combines beautifully with generics. It preserves all of thetype safety, while removing the remaining clutter. Because you don't have todeclare the iterator, you don't have to provide a generic declaration for it.(The compiler does this for you behind your back, but you need not concernyourself with it.)

 

Here is a common mistake people make whenthey are trying to do nested iteration over two collections:

 

List suits = ...;

List ranks = ...;

List sortedDeck = new ArrayList();

 

// BROKEN - throws NoSuchElementException!

for (Iterator i = suits.iterator();i.hasNext(); )

for (Iterator j = ranks.iterator();j.hasNext(); )

sortedDeck.add(new Card(i.next(),j.next()));

 

Can you spot the bug? Don't feel bad if youcan't. Many expert programmers have made this mistake at one time or another.The problem is that the next method is being called too many times on the“outer” collection (suits). It is being called in the inner loop for both theouter and inner collections, which is wrong. In order to fix it, you have toadd a variable in the scope of the outer loop to hold the suit:

 

// Fixed, though a bit ugly

for (Iterator i = suits.iterator();i.hasNext(); ) {

Suit suit = (Suit) i.next();

for (Iterator j = ranks.iterator();j.hasNext(); )

sortedDeck.add(new Card(suit, j.next()));

}

 

So what does all this have to do with thefor-each construct? It is tailor-made for nested iteration! Feast your eyes:

 

for (Suit suit : suits)

for (Rank rank : ranks)

sortedDeck.add(new Card(suit, rank));

 

The for-each construct is also applicableto arrays, where it hides the index variable rather than the iterator. Thefollowing method returns the sum of the values in an int array:

 

// Returns the sum of the elements of a

int sum(int[] a) {

int result = 0;

for (int i : a)

result += i;

return result;

}

 

So when should you use the for-each loop?Any time you can. It really beautifies your code. Unfortunately, you cannot useit everywhere. Consider, for example, the expurgate method. The program needsaccess to the iterator in order to remove the current element. The for-eachloop hides the iterator, so you cannot call remove. Therefore, the for-eachloop is not usable for filtering. Similarly it is not usable for loops whereyou need to replace elements in a list or array as you traverse it. Finally, itis not usable for loops that must iterate over multiple collections inparallel. These shortcomings were known by the designers, who made a consciousdecision to go with a clean, simple construct that would cover the greatmajority of cases.

 

7.元数据

 

元数据,在java中也叫注释、注解。微软的.net从开始设计时就有这个功能,不过它的术语叫属性。

在将来的j2ee开发中,广泛的使用它,包括ejb的声明,IOC中的注入等。

 

元数据,在java中也叫注释、注解。微软的.net从开始设计时就有这个功能,不过它的术语叫属性。

 

这时一个强大的功能,程序员如果想挣钱,得好好研究它,因为

 

在将来的j2ee开发中,广泛的使用它,包括ejb的声明,IOC中的注入等。

 

 

IBM网站有篇文章详细介绍了它,挺好的一篇文章。

 

http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/

 

http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml

 

 

 

我曾兴致勃勃的根据例子在eclipse中测试了一把,可怎么也得不到注释信息。后来,在命令行直接编译java文件,运行才正常。虽然现在的eclipse 编辑器可以识别java的注释语法,但是在编译的时候并没有生成带注释的java类。我没有仔细深究,可能时eclipse在编译的时候枚加上-target 5参数吧,猜测而已。

 

新建一个注释类型,这个类型指明了一本名著的作者和他的email。

 

   package com.kuaff.jdk5;

     

   import java.lang.annotation.*;

     

   @Retention(RetentionPolicy.RUNTIME)

   @Target(ElementType.METHOD)

   public @interface BookAuthor 

    {

       String name(); 

          String email();

    }

     

     

 

 

使用这个注释为我们的方法加上注解:

 

   package com.kuaff.jdk5;

     

   import java.lang.annotation.Annotation;

     

   public class MetadataShow

    {

        @BookAuthor(name="曹雪芹",email="caoxueqin@hongloumeng.books") 

       public void introHongLouMeng()

        {

           System.out.println("这是一本好书啊");

        }

     

       public static void main(String[] args)

        {

            MetadataShow metadata = new MetadataShow();

           try

            {

                Annotation[] annotation =metadata.getClass().getMethod("introHongLouMeng").getAnnotations();

                for(Annotation   a : annotation)

                 {

                    System.out.printf("作者:%s%n",((BookAuthor)a).name());

                    System.out.printf("他的电子邮件(可能已被注销):%s%n",((BookAuthor)a).email());

                 }

            }

           catch (SecurityException e)

            {

                 e.printStackTrace();

            }

           catch (NoSuchMethodException e)

            {

                 e.printStackTrace();

            }

        }

    }

     

      

 

请注意,要想在程序运行时能读取这些注释,需要在注释的声明的时候加上

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD) //也可能时其他类型,如针对声明的注释

 

这是对注释的注释。

编译这两个文件:

javac-source 5 -target 5 -d bin src/com/kuaff/jdk5/*.java


转载自:http://blog.csdn.net/j2eeweiwei/article/details/3932775

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值