码迷,mamicode.com
首页 > 编程语言 > 详细

java5 新特性

时间:2015-10-22 00:23:31      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

1.静态导入方法 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. /** 
  4.  *  
  5.  * 一般我们导入一个类都用 import com.....ClassName;而静态导入是这样:import static com.....ClassName.*; 
  6.  * 这里的多了个static,还有就是类名ClassName后面多了个 .* ,意思是导入这个类里的静态方法。当然,也可以只导入某个静态方法,只要把 .* 换成静态方法名就行了。 
  7.  * 然后在这个类中,就可以直接用方法名调用静态方法,而不必用ClassName.方法名 的方式来调用。 
  8.  * 这种方法的好处就是可以简化一些操作,例如打印操作System.out.println(...);就可以将其写入一个静态方法print(...),在使用时直接print(...)就可以了。 
  9.  * 但是这种方法建议在有很多重复调用的时候使用,如果仅有一到两次调用,不如直接写来的方便。 
  10.  
  11.  * @author yuahan 
  12.  * 
  13.  */  
  14. public class _Static_Import {  
  15.     public static void main(String[] args) {  
  16.   
  17.     }  
  18. }  



2.新增加的for循环 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. /** 
  7.  * 增强的for循环,可以使用在数组和容器中 
  8.  * @author yuahan 
  9.  * 
  10.  */  
  11. public class _For {  
  12.     @SuppressWarnings("serial")  
  13.     public static void main(String[] args) {  
  14.         int[] array = {1,2,3,4,5,6,7,8,9,10};  
  15.         for(int num : array){  
  16.             System.out.print(num + " ");  
  17.         }  
  18.           
  19.         System.out.println();  
  20.           
  21.         List<Integer> list = new ArrayList<Integer>(){{  
  22.             this.add(1);  
  23.             this.add(2);  
  24.             this.add(3);  
  25.             this.add(4);  
  26.             this.add(5);  
  27.             this.add(6);  
  28.             this.add(7);  
  29.             this.add(8);  
  30.             this.add(9);  
  31.             this.add(10);  
  32.         }};  
  33.           
  34.         for(int num : list){  
  35.             System.out.print(num + " ");  
  36.         }  
  37.     }  
  38. }  




3.枚举 Enum 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. /** 
  4.  *  
  5.  * 你可以将枚举类型视为特殊的类,因此几乎可以像创建普通类那样创建枚举。 
  6.  * 枚举类型有附加的特性,有EnumMap和EnumSet两个类。实例化方法中都需要传入枚举类型的类类型,如: 
  7.  *  EnumSet<_Enum> set = EnumSet.noneOf(_Enum.class); 
  8.     EnumMap<_Enum,String> map = new EnumMap<_Enum,String>(_Enum.class); 
  9.      
  10.     枚举可以有自己的构造方法,不过构造方法只能私有,这样外部是不能构造出新的枚举中的实例,而只是调用其中的实例。 
  11.  * @author yuahan 
  12.  * 
  13.  */  
  14. public enum _Enum {  
  15.     Better(90),  
  16.     Good(80),  
  17.     Ok(70),  
  18.     Bad(60),  
  19.     Worse;  
  20.       
  21.     private int value;  
  22.   
  23.     private _Enum() {  
  24.         this.value = 30;  
  25.     }  
  26.       
  27.     private _Enum(int value) {  
  28.         this.value = value;  
  29.     }  
  30.       
  31.     public int getValue() {  
  32.         return value;  
  33.     }  
  34.   
  35.     public void setValue(int value) {  
  36.         this.value = value;  
  37.     }  
  38.   
  39.     public static _Enum[] getEnumValues(){  
  40.         return _Enum.values();  
  41.     }  
  42.       
  43.     public static void _ValuesOf(){  
  44. //      _Enum test = _Enum.valueOf("test");//error  
  45. //      System.out.println(test);  
  46.           
  47.         _Enum Better = _Enum.valueOf("Better");  
  48.         System.out.println(Better);  
  49.     }  
  50.       
  51.       
  52.     public static void main(String[] args) {  
  53.         for(_Enum mark : _Enum.getEnumValues()){  
  54.             switch(mark){  
  55.             case Better:  
  56.                 System.out.println(_Enum.Better);  
  57.                 break;  
  58.             case Good:  
  59.                 System.out.println(_Enum.Good);  
  60.                 break;  
  61.             case Ok:  
  62.                 System.out.println(_Enum.Ok);  
  63.                 break;  
  64.             case Bad:  
  65.                 System.out.println(_Enum.Bad);  
  66.                 break;  
  67.             case Worse:  
  68.                 System.out.println(_Enum.Worse);  
  69.                 break;    
  70.             }  
  71.         }  
  72.           
  73.         _Enum._ValuesOf();  
  74.           
  75.         System.out.println(_Enum.Better.getValue());  
  76.     }  
  77. }  




4.反射 Reflect 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. import java.lang.reflect.Array;  
  4. import java.lang.reflect.Constructor;  
  5. import java.lang.reflect.Field;  
  6. import java.lang.reflect.Method;  
  7. import java.lang.reflect.Modifier;  
  8. import java.util.Arrays;  
  9.   
  10. /** 
  11.  * Reflection 是 Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查,或者说“自审”,并能直接操作程序的内部属性。 
  12.  * Java 的这一能力在实际应用中也许用得不是很多,但是在其它的程序设计语言中根本就不存在这一特性 
  13.  * JavaDoc 中对每个类和其中的方法有非常详细介绍。主要有: 
  14.   
  15.  * Class   ------- java.lang 
  16.  * Package ------- java.lang 
  17.  *  
  18.  * Array 
  19.  * Field 
  20.  * Method 
  21.  * Modifier 
  22.  * Constructor 
  23.  * @author yuahan 
  24.  * 
  25.  */  
  26. public class _Reflect {  
  27.     private int id;  
  28.     private String name;  
  29.     private String[] hobbies;  
  30.       
  31.     public _Reflect(){}  
  32.       
  33.     public _Reflect(int id){  
  34.         this.id = id;  
  35.     }  
  36.       
  37.     public _Reflect(int id, String name, String[] hobbies) {  
  38.         super();  
  39.         this.id = id;  
  40.         this.name = name;  
  41.         this.hobbies = hobbies;  
  42.     }  
  43.   
  44.     public int getId() {  
  45.         return id;  
  46.     }  
  47.   
  48.     public void setId(int id) {  
  49.         this.id = id;  
  50.     }  
  51.   
  52.     public String getName() {  
  53.         return name;  
  54.     }  
  55.   
  56.     public void setName(String name) {  
  57.         this.name = name;  
  58.     }  
  59.   
  60.     public String[] getHobbies() {  
  61.         return hobbies;  
  62.     }  
  63.   
  64.     public void setHobbies(String[] hobbies) {  
  65.         this.hobbies = hobbies;  
  66.     }  
  67.       
  68.     public static void main(String[] args) throws Exception{  
  69.         //---------------------------------basic---------------------------------  
  70.         System.out.println(_Reflect.class.getSimpleName());  
  71.         System.out.println(_Reflect.class.getName());  
  72.         System.out.println(_Reflect.class.getPackage());   
  73.         System.out.println(_Reflect.class.getSuperclass().getName());  
  74.         System.out.println(int[].class.getName());   
  75.         System.out.println(_Reflect[].class.getName());        
  76.           
  77.           
  78. //      //--------------------------------- Method ---------------------------------  
  79.         Method[] methods = _Reflect.class.getMethods();  
  80.         for(Method method : methods){  
  81.             System.out.println(method + ": " +method.getDeclaringClass().getName());  
  82.         }  
  83.           
  84.           
  85.           
  86. //      //--------------------------------- isXXX ---------------------------------   
  87.         System.out.println(Comparable.class.isInterface());  
  88.         System.out.println(int.class.isPrimitive());  
  89.         System.out.println(int[].class.isArray());  
  90.           
  91.           
  92.           
  93. //      //--------------------------------- Modifier 修饰符 ---------------------------------  
  94.         System.out.println(Modifier.isPublic(_Reflect.class.getModifiers()));  
  95.           
  96.         Class<?>[] classes = null;  
  97.         System.out.println(Modifier.isPublic(_Reflect.class.getMethod("getId",classes).getModifiers()));  
  98.           
  99.           
  100.         //isAssignableFrom    isInstance  
  101.         System.out.println(Number.class.isAssignableFrom(Integer.class));  
  102.         System.out.println(Number.class.isInstance(1));  
  103.           
  104.           
  105.         //---------------------------------Field---------------------------------  
  106.         _Reflect _Reflect = new _Reflect();  
  107.         System.out.println(_Reflect.getId());  
  108.         System.out.println(_Reflect.getName());  
  109.         System.out.println(Arrays.toString(_Reflect.getHobbies()));  
  110.           
  111.         Field[] fields = _Reflect.class.getDeclaredFields();  
  112.         for(Field field : fields){  
  113.             if(field.getType() == int.class){  
  114.                 field.setAccessible(true);  
  115.                 field.setInt(_Reflect, 1);  
  116.             }else if(field.getType() == String.class){  
  117.                 field.setAccessible(true);  
  118.                 field.set(_Reflect, "1");  
  119.             }else if(field.getType() == String[].class){  
  120.                 field.setAccessible(true);  
  121.                 field.set(_Reflect, new String[]{"1","1"});  
  122.             }  
  123.         }  
  124.           
  125.         System.out.println(_Reflect.getId());  
  126.         System.out.println(_Reflect.getName());  
  127.         System.out.println(Arrays.toString(_Reflect.getHobbies()));  
  128.           
  129.           
  130. //      //---------------------------------new instance---------------------------------  
  131.         Constructor<_Reflect> constructor = _Reflect.class.getConstructor(new Class[]{int.class,String.class,String[].class});  
  132.         _Reflect _reflect = constructor.newInstance(new Object[]{1,"1",new String[]{"1","1"}});  
  133.         System.out.println(_reflect.getId());  
  134.         System.out.println(_reflect.getName());  
  135.         System.out.println(Arrays.toString(_Reflect.getHobbies()));  
  136.   
  137.           
  138.         Class<?> clazz = Class.forName("com.java.new_features_jdk5._Reflect");  
  139.         _Reflect clazzes = (_Reflect)clazz.newInstance();  
  140.         System.out.println(clazzes.getId());  
  141.         System.out.println(clazzes.getName());  
  142.         System.out.println(Arrays.toString(clazzes.getHobbies()));  
  143.           
  144.           
  145.           
  146.           
  147.         //---------------------------------Array---------------------------------  
  148.         //---------------------------------0---------------------------------  
  149.         int[] ints0 = (int[])Array.newInstance(int.class, 3);  
  150.         Array.setInt(ints0, 0, 0);  
  151.         Array.setInt(ints0, 1, 1);  
  152.         Array.setInt(ints0, 2, 2);  
  153. //    //Array.setInt(ints, 3, 3); //java.lang.ArrayIndexOutOfBoundsException  
  154.         System.out.println(Arrays.toString(ints0));  
  155.           
  156.           
  157.         //---------------------------------1---------------------------------  
  158.         int[][][] ints3 = (int[][][])Array.newInstance(int.class,2,3,4);  
  159.           
  160.         System.out.println(ints3.length);  
  161.         System.out.println(ints3[0].length);  
  162.         System.out.println(ints3[0][0].length);  
  163.           
  164.         int[][] ints3_1_row0_content = new int[][]{{1,2,3,4},{1,2,3,4},{1,2,3,4}};  
  165.         int[][] ints3_1_row1_content = new int[][]{{11,22,33,44},{11,22,33,44},{11,22,33,44}};  
  166.         Array.set(ints3, 0, ints3_1_row0_content);  
  167.         Array.set(ints3, 1, ints3_1_row1_content);  
  168.         System.out.println(Arrays.deepToString(ints3));  
  169.           
  170.           
  171.         //---------------------------------2---------------------------------  
  172.         int[][] ints2 = (int[][])Array.newInstance(int.class, 4,4);  
  173.         for (int i=0; i<4; i++) {  
  174.             ints2[i] = (int[]) Array.newInstance(int.class, i + 1);//重新创建每个第一位数组的长度  
  175.         }  
  176.         for(int[] array : ints2){  
  177.             for(int content : array){  
  178.                 System.out.print(content + ",");  
  179.             }  
  180.             System.out.println();  
  181.         }  
  182.   
  183.           
  184.         //---------------------------------4---------------------------------  
  185.         int[][][] ints4 = new int[1][2][3];  
  186.         Class<?> clazzz = ints4.getClass();  
  187.         int dim = 0;  
  188.         while(clazzz.isArray()){  
  189.             dim ++;  
  190.             clazzz = clazzz.getComponentType();  
  191.         }  
  192.         System.out.println(dim);  
  193.           
  194.         System.out.println(ints4.getClass().isArray());  
  195.         System.out.println(ints4.getClass().getComponentType().getName());  
  196.         System.out.println(ints4.getClass().getComponentType().getComponentType().getName());  
  197.         System.out.println(ints4.getClass().getComponentType().getComponentType().getComponentType().getName());  
  198. //      System.out.println(ints2.getClass().getComponentType().getComponentType().getComponentType().getComponentType().getName());//java.lang.NullPointerException  
  199.           
  200.     }  
  201. }  




5.注解 Annotation 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. /** 
  4.  * 比较常用的注释: 
  5.  *  SuppressWarnings    指示应该在注释元素(以及包含在该注释元素中的所有程序元素)中取消显示指定的编译器警告。 
  6.     Deprecated          用"@Deprecated" 注释的程序元素,不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。在使用不被赞成的程序元素或在不被赞成的代码中执行重写时,编译器会发出警告。  
  7.     Override            表示一个方法声明打算重写超类中的另一个方法声明。如果方法利用此注释类型进行注解但没有重写超类方法,则编译器会生成一条错误消息。 
  8.  * @author yuahan 
  9.  * 
  10.  */  
  11. public class _Annotation {  
  12.     public static void main(String[] args) {  
  13.           
  14.     }  
  15. }  




6.泛型 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.List;  
  6.   
  7. /** 
  8.  * Java语言的泛型类似于C++中的模板. 但是这仅仅是基于表面的现象。Java语言的泛型基本上完全在编译器中实现的,由编译器执行类型检查和类型推断,然后生成普通的非泛型的字节码。 这种实现称为"擦除"(编译器使用泛型类型信息保证类型安全,然后在生成字节码之前将其清除) 
  9.     需要注意的地方: 
  10.  *  1. 泛型不是协变的 
  11.         协变:Java 语言中的数组是协变的(covariant),也就是说, 如果 Integer 扩展了 Number,那么不仅 Integer 是 Number,而且 Integer[] 也是 Number[],在要求Number[] 的地方完全可以传递或者赋予 Integer[]。 
  12.         但是,泛型并不是协变的。  如果Number是Integer的超类型,但是,如果需要List<Integer>的时候, 并不容许传递List<Number>,它们并不等价。 
  13.         不允许的理由很简单,这样会破坏要提供的类型安全泛型。 
  14.         如: 
  15.         public static void main(String[] args) { 
  16.             List<Integer> list=new ArrayList<Integer>(); 
  17.             List<Number> list2=list;//编译错误. 
  18.             list2.add(new Float(19.0f)); 
  19.         } 
  20.      
  21.     2. 延迟构造 
  22.         因为可以擦除功能,所以List<Integer>和List<String>是同一个类,编译器在编译List<V>的时候,只生成一个类。所以,运行时,不能区分List<Integer>和List<String>(实际上,运行时都是List,类型被擦除了), 
  23.         用泛型类型参数标识类型的变量的构造就成了问题。运行时缺乏类型信息,这给泛型容器类和希望创建保护性副本的泛型类提出了难题。 
  24.      
  25.     3. 不能用通配符来帮助构造一个类(容器,数组等),因为根本不知道类型,不能确定该构造函数是否存在 
  26.         class Foo{ 
  27.             public void doSomething(Set<?> set){ 
  28.                 Set<?> copy = new HashSet<?>(set);//编译出错,不能用通配符类型的参数调用泛型构造函数 
  29.             } 
  30.         } 
  31.          
  32.         或者 
  33.          
  34.         class ArrayList<V>{ 
  35.             V[] content; 
  36.             public ArrayList() { 
  37.                 content = new V[10];//编译出错,不能实例化用类型参数表示的类型数组 
  38.             } 
  39.         } 
  40.          
  41.         不过可以用Object类帮助实现,不过看上去很不舒服。 
  42.         class Foo{ 
  43.             public void doSomething(Set<?> set){ 
  44.                 Set<?> copy = new HashSet<Object>(set); 
  45.             } 
  46.         } 
  47.          
  48.         或者 
  49.          
  50.         class ArrayList<V>{ 
  51.             V[] content; 
  52.             public ArrayList() { 
  53.                 content = (V[])new Object[10]; 
  54.             } 
  55.         } 
  56.     4. 擦除 
  57.          因为泛型基本上都是在JAVA编译器中而不是运行库中实现的,所以在生成字节码的时候,差不多所有关于泛型类型的类型信息都被“擦除”了, 换句话说,编译器生成的代码与手工编写的不用泛型、检查程序类型安全后进行强制类型转换所得到的代码基本相同。 
  58.          擦除意味着,一个类不能同时实现 Comparable<String>和Comparable<Number>,因为事实上,两者都在同一个接口中,指定同一个compareTo()方法。 
  59.     5.  泛型的规则和限制 
  60.         (1  泛型的参数类型只能是类( class )类型,而不能是简单类型。 
  61.               比如, <int> 是不可使用的。 
  62.         (2 可以声明多个泛型参数类型,比如 <T, P,Q…> ,同时还可以嵌套泛型,例如: <List<String>>. 
  63.         (3  泛型 的参数 类 型可以使用 extends 语 句,例如 <T extends superclass> 。 
  64.         (4  泛型的参数类型可以使用 super 语句,例如 < T super childclass> 。 
  65.         (5 泛型还可以使用通配符,例如 <? e xtends ArrayList> 
  66.  * @author yuahan 
  67.  * 
  68.  */  
  69. public class _Generic <T> {  
  70.     public void array2Collection(T[] array, Collection<T> collection){  
  71.         if(array != null && collection != null){  
  72.             for(T content : array ){  
  73.                 collection.add(content);  
  74.             }  
  75.         }  
  76.     }  
  77.     public static void main(String[] args) {  
  78.         _Generic<Integer> generic = new _Generic<Integer>();  
  79.         Integer[] array = new Integer[]{1,2,3,4};  
  80.         List<Integer> list = new ArrayList<Integer>();  
  81.         generic.array2Collection(array, list);  
  82.         System.out.println(list);  
  83.     }  
  84. }  




7.可变参数(Vararg) 

Java代码  技术分享
  1. package com.java.new_features_jdk5;  
  2.   
  3. /** 
  4.  *  
  5.  * 可变参数可以解决代码冗余的问题。 
  6.  * 如: 
  7.  * public int max(int i, int j); 
  8.  * public int max(int i, int j, int k); 
  9.  * 可以简化成 
  10.  * public int max(int... num); 
  11.  *  
  12.  * 可以将可变参数视为长度可变的数组。不过需要注意以下问题 : 
  13.  *  1. 变长参数一定要放在最后面 
  14.     max(int ... nums, int temp)// error 
  15.  *  2. 可变参数不能与数组参数并存 
  16.     max(int[] nums)//error 
  17.  
  18.  * @author yuahan 
  19.  * 
  20.  */  
  21. public class _Var_Arg {  
  22.       
  23.     public static int max(int ... nums){  
  24.         int max = Integer.MIN_VALUE;  
  25.         for(int num : nums){  
  26.             if(num >= max){  
  27.                 max = num;  
  28.             }  
  29.         }  
  30.         return max;  
  31.     }  
  32.       
  33.       
  34.     public static void main(String[] args) {  
  35.         int max1 = _Var_Arg.max(1,2,3,4,5);  
  36.         int max2 = _Var_Arg.max(new int[]{1,2,3,4,5});  
  37.         System.out.println(max1);  
  38.         System.out.println(max2);  
  39.     }  
  40. }  




8.格式化输入输出 
不太喜欢c的输出格式,没有进行尝试。

java5 新特性

标签:

原文地址:http://www.cnblogs.com/tian830937/p/4899437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!