Java5:
1、泛型 Generics:
引用泛型之後,允許指定集合裏元素的類型,免去了強制類型轉換,並且能在編譯時刻進行類型檢查的好處。
Parameterized Type作爲參數和返回值,Generic是vararg、annotation、enumeration、collection的基石。
A、類型安全
拋棄List、Map,使用List<T>、Map<K,V>給它們添加元素或者使用Iterator<T>遍歷時,編譯期就可以給你檢查出類型錯誤B、方法參數和返回值加上了Type
拋棄List、Map,使用List<T>、Map<K,V>
C、不需要類型轉換
List<String> list=new ArrayList<String>();
String str=list.get(i);
D、類型通配符“?”假設一個打印List<T>中元素的方法printList,我們希望任何類型T的List<T>都可以被打印:
代碼:
- public void printList(List<?> list,PrintStream out)throws IOException{
- for(Iterator<?> i=list.iterator();i.hasNext();){
- System.out.println(i.next.toString());
- }
- }
如果通配符?讓我們的參數類型過於廣泛,我們可以把List<?>、Iterator<?> 修改爲
List<? Extends Number>、Iterator<? Extends Number>限制一下它。
2、枚舉類型 Enumeration:
3、自動裝箱拆箱(自動類型包裝和解包)autoboxing & unboxing:
簡單的說是類型自動轉換。
自動裝包:基本類型自動轉爲包裝類(int ——Integer)
自動拆包:包裝類自動轉爲基本類型(Integer——int)
4、可變參數varargs(varargs number of arguments)
參數類型相同時,把重載函數合併到一起了。
如:public void test(object… objs){
for(Object obj:objs){
System.out.println(obj);
}
}
5、Annotations 它是java中的metadata(註釋)
A、Tiger中預定義的三種標準annotation
a 、Override
指出某個method覆蓋了superclass 的method當你要覆蓋的方法名拼寫錯時編譯不通過
b、Deprecated
指出某個method或element類型的使用是被阻止的,子類將不能覆蓋該方法
c、SupressWarnings
關閉class、method、field、variable 初始化的編譯期警告,比如:List沒有使用 Generic,則@SuppressWarnings(“unchecked”)去掉編譯期警告。
B、自定義annotation
public @interface Marked{}
C、meta-annotation
或者說annotation的annotation
四種標準的meta-annotation全部定義在java.lang.annotaion包中:
a, Target
指定所定義的annotation可以用在哪些程序單元上
如果Target沒有指定,則表示該annotation可以使用在任意程序單元上
代碼
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ ElementType.FIELD, ElementType.METHOD })
- public @interface RejectEmpty {
- /** hint title used in error message */
- String value() default “”;
- }
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.FIELD, ElementType.METHOD })
- public @interface AcceptInt {
- int min() default Integer.MIN_VALUE;
- int max() default Integer.MAX_VALUE;
- String hint() default “”;
- }
b, Retention
指出Java編譯期如何對待annotation
annotation可以被編譯期丟掉,或者保留在編譯過的class文件中
在annotation被保留時,它也指定是否會在JVM加載class時讀取該annotation
代碼
- @Retention(RetentionPolicy.SOURCE) // Annotation會被編譯期丟棄
- public @interface TODO1 {}
- @Retention(RetentionPolicy.CLASS) // Annotation保留在class文件中,但會被JVM忽略
- public @interface TODO2 {}
- @Retention(RetentionPolicy.RUNTIME) // Annotation保留在class文件中且會被JVM讀取
- 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對象驗證
代碼
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ ElementType.FIELD, ElementType.METHOD })
- public @interface RejectEmpty {
- /** hint title used in error message */
- String value() default “”;
- }
- @Retention(RetentionPolicy.RUNTIME)
- @Target( { ElementType.FIELD, ElementType.METHOD })
- public @interface AcceptInt {
- int min() default Integer.MIN_VALUE;
- int max() default Integer.MAX_VALUE;
- String hint() default “”;
- }
6、新的迭代語句(for(int n:numbers))
7、靜態導入(import static )
8、新的格式化方法(java.util.Formatter)
formatter.format(“Remaining account balance: $%.2f”, balance);
9、新的線程模型和併發庫Thread Framework
HashMap的替代者ConcurrentHashMap和ArrayList的替代者CopyOnWriteArrayList
在大併發量讀取時採用java.util.concurrent包裏的一些類會讓大家滿意BlockingQueue、Callable、Executor、Semaphore…
1、引入了一個支持腳本引擎的新框架
2、UI的增強
3、對WebService支持的增強(JAX-WS2.0和JAXB2.0)
4、一系列新的安全相關的增強
5、JDBC4.0
6、Compiler API
7、通用的Annotations支持
Java7:
1,switch中可以使用字串了
- String s = “test”;
- switch (s) {
- case “test” :
- System.out.println(”test”);
- case “test1” :
- System.out.println(”test1”);
- break ;
- default :
- System.out.println(”break”);
- break ;
- }
2.運用List<String> tempList = new ArrayList<>(); 即泛型實例化類型自動推斷
3.語法上支持集合,而不一定是數組
final List<Integer> piDigits = [ 1,2,3,4,5,8 ];
4.新增一些取環境信息的工具方法
- File System.getJavaIoTempDir() // IO臨時文件夾
- File System.getJavaHomeDir() // JRE的安裝目錄
- File System.getUserHomeDir() // 當前用戶目錄
- File System.getUserDir() // 啓動java進程時所在的目錄5
5.Boolean類型反轉,空指針安全,參與位運算
- Boolean Booleans.negate(Boolean booleanObj)
- True => False , False => True, Null => Null
- boolean Booleans.and(boolean[] array)
- boolean Booleans.or(boolean[] array)
- boolean Booleans.xor(boolean[] array)
- boolean Booleans.and(Boolean[] array)
- boolean Booleans.or(Boolean[] array)
- boolean Booleans.xor(Boolean[] array)
6.兩個char間的equals
boolean Character.equalsIgnoreCase(char ch1, char ch2)
7.安全的加減乘除
- int Math.safeToInt(long value)
- int Math.safeNegate(int value)
- long Math.safeSubtract(long value1, int value2)
- long Math.safeSubtract(long value1, long value2)
- int Math.safeMultiply(int value1, int value2)
- long Math.safeMultiply(long value1, int value2)
- long Math.safeMultiply(long value1, long value2)
- long Math.safeNegate(long value)
- int Math.safeAdd(int value1, int value2)
- long Math.safeAdd(long value1, int value2)
- long Math.safeAdd(long value1, long value2)
- int Math.safeSubtract(int value1, int value2)
8.map集合支持併發請求,且可以寫成 Map map = {name:”xxx”,age:18};
JAVA8:
java8的新特新逐一列出,並將使用簡單的代碼示例來指導你如何使用默認接口方法,lambda表達式,方法引用以及多重Annotation,之後你將會學到最新的API上的改進,比如流,函數式接口,Map以及全新的日期API
一、接口的默認方法
Java 8允許我們給接口添加一個非抽象的方法實現,只需要使用 default關鍵字即可,這個特徵又叫做擴展方法,示例如下:
- interface Formula {
- double calculate(int a);
- default double sqrt(int a) {
- return Math.sqrt(a);
- }
- }
Formula接口在擁有calculate方法之外同時還定義了sqrt方法,實現了Formula接口的子類只需要實現一個calculate方法,默認方法sqrt將在子類上可以直接使用。
- Formula formula = new Formula() {
- @Override
- public double calculate(int a) {
- return sqrt(a * 100);
- }
- };
- formula.calculate(100); // 100.0
- formula.sqrt(16); // 4.0
文中的formula被實現爲一個匿名類的實例,該代碼非常容易理解,6行代碼實現了計算 sqrt(a * 100)。在下一節中,我們將會看到實現單方法接口的更簡單的做法。譯者注: 在Java中只有單繼承,如果要讓一個類賦予新的特性,通常是使用接口來實現,在C++中支持多繼承,允許一個子類同時具有多個父類的接口與功能,在其他語言中,讓一個類同時具有其他的可複用代碼的方法叫做mixin。新的Java
8 的這個特新在編譯器實現的角度上來說更加接近Scala的trait。 在C#中也有名爲擴展方法的概念,允許給已存在的類型擴展方法,和Java 8的這個在語義上有差別。
二、Lambda 表達式
首先看看在老版本的Java中是如何排列字符串的:
- List<String> names = Arrays.asList(“peter”, “anna”, “mike”, “xenia”);
- Collections.sort(names, new Comparator<String>() {
- @Override
- public int compare(String a, String b) {
- return b.compareTo(a);
- }
- });
只需要給靜態方法 Collections.sort 傳入一個List對象以及一個比較器來按指定順序排列。通常做法都是創建一個匿名的比較器對象然後將其傳遞給sort方法。在Java 8 中你就沒必要使用這種傳統的匿名對象的方式了,Java 8提供了更簡潔的語法,lambda表達式:
- Collections.sort(names, (String a, String b) -> {
- return b.compareTo(a);
- });
看到了吧,代碼變得更段且更具有可讀性,但是實際上還可以寫得更短:
- Collections.sort(names, (String a, String b) -> b.compareTo(a));
看到了吧,代碼變得更段且更具有可讀性,但是實際上還可以寫得更短:
- Collections.sort(names, (String a, String b) -> b.compareTo(a));
對於函數體只有一行代碼的,你可以去掉大括號{}以及return關鍵字,但是你還可以寫得更短點:
- Collections.sort(names, (a, b) -> b.compareTo(a));
Java編譯器可以自動推導出參數類型,所以你可以不用再寫一次類型。接下來我們看看lambda表達式還能作出什麼更方便的東西來:
三、函數式接口
Lambda表達式是如何在java的類型系統中表示的呢?每一個lambda表達式都對應一個類型,通常是接口類型。而“函數式接口”是指僅僅只包含一個抽象方法的接口,每一個該類型的lambda表達式都會被匹配到這個抽象方法。因爲 默認方法 不算抽象方法,所以你也可以給你的函數式接口添加默認方法。
我們可以將lambda表達式當作任意只包含一個抽象方法的接口類型,確保你的接口一定達到這個要求,你只需要給你的接口添加 @FunctionalInterface 註解,編譯器如果發現你標註了這個註解的接口有多於一個抽象方法的時候會報錯的。
- @FunctionalInterface
- interface Converter<F, T> {
- T convert(F from);
- }
- Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
- Integer converted = converter.convert(”123”);
- System.out.println(converted); // 123
譯者注 將lambda表達式映射到一個單方法的接口上,這種做法在Java 8之前就有別的語言實現,比如Rhino JavaScript解釋器,如果一個函數參數接收一個單方法的接口而你傳遞的是一個function,Rhino 解釋器會自動做一個單接口的實例到function的適配器,典型的應用場景有 org.w3c.dom.events.EventTarget 的addEventListener 第二個參數 EventListener。
四、方法與構造函數引用
前一節中的代碼還可以通過靜態方法引用來表示:
- Converter<String, Integer> converter = Integer::valueOf;
- Integer converted = converter.convert(”123”);
- System.out.println(converted); // 123
Java 8 允許你使用 :: 關鍵字來傳遞方法或者構造函數引用,上面的代碼展示瞭如何引用一個靜態方法,我們也可以引用一個對象的方法:
- converter = something::startsWith;
- String converted = converter.convert(”Java”);
- System.out.println(converted); // “J”
接下來看看構造函數是如何使用::關鍵字來引用的,首先我們定義一個包含多個構造函數的簡單類:
- class Person {
- String firstName;
- String lastName;
- Person() {}
- Person(String firstName, String lastName) {
- this.firstName = firstName;
- this.lastName = lastName;
- }
- }
接下來我們指定一個用來創建Person對象的對象工廠接口:
- interface PersonFactory<P extends Person> {
- P create(String firstName, String lastName);
- }
這裏我們使用構造函數引用來將他們關聯起來,而不是實現一個完整的工廠:
- PersonFactory<Person> personFactory = Person::new;
- Person person = personFactory.create(”Peter”, “Parker”);
我們只需要使用 Person::new 來獲取Person類構造函數的引用,Java編譯器會自動根據PersonFactory.create方法的簽名來選擇合適的構造函數。
五、Lambda 作用域
在lambda表達式中訪問外層作用域和老版本的匿名對象中的方式很相似。你可以直接訪問標記了final的外層局部變量,或者實例的字段以及靜態變量。
六、訪問局部變量
我們可以直接在lambda表達式中訪問外層的局部變量:
- final int num = 1;
- Converter<Integer, String> stringConverter =(from) -> String.valueOf(from + num);
- stringConverter.convert(2); // 3
但是和匿名對象不同的是,這裏的變量num可以不用聲明爲final,該代碼同樣正確:
- int num = 1;
- Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
- stringConverter.convert(2); // 3
不過這裏的num必須不可被後面的代碼修改(即隱性的具有final的語義),例如下面的就無法編譯:
- int num = 1;
- Converter<Integer, String> stringConverter =
- (from) -> String.valueOf(from + num);
- num = 3;
在lambda表達式中試圖修改num同樣是不允許的。
七、訪問對象字段與靜態變量
和本地變量不同的是,lambda內部對於實例的字段以及靜態變量是即可讀又可寫。該行爲和匿名對象是一致的:
- class Lambda4 {
- static int outerStaticNum;
- int outerNum;
- void testScopes() {
- Converter<Integer, String> stringConverter1 = (from) -> {
- outerNum = 23;
- return String.valueOf(from);
- };
- Converter<Integer, String> stringConverter2 = (from) -> {
- outerStaticNum = 72;
- return String.valueOf(from);
- };
- }
- }
八、訪問接口的默認方法
還記得第一節中的formula例子麼,接口Formula定義了一個默認方法sqrt可以直接被formula的實例包括匿名對象訪問到,但是在lambda表達式中這個是不行的。
Lambda表達式中是無法訪問到默認方法的,以下代碼將無法編譯:
- Formula formula = (a) -> sqrt( a * 100);
- Built-in Functional Interfaces
JDK 1.8 API包含了很多內建的函數式接口,在老Java中常用到的比如Comparator或者Runnable接口,這些接口都增加了@FunctionalInterface註解以便能用在lambda上。
Java 8 API同樣還提供了很多全新的函數式接口來讓工作更加方便,有一些接口是來自Google Guava庫裏的,即便你對這些很熟悉了,還是有必要看看這些是如何擴展到lambda上使用的。
Predicate接口
Predicate 接口只有一個參數,返回boolean類型。該接口包含多種默認方法來將Predicate組合成其他複雜的邏輯(比如:與,或,非):
- Predicate<String> predicate = (s) -> s.length() > 0;
- predicate.test(”foo”); // true
- predicate.negate().test(”foo”); // false
- Predicate<Boolean> nonNull = Objects::nonNull;
- Predicate<Boolean> isNull = Objects::isNull;
- Predicate<String> isEmpty = String::isEmpty;
- Predicate<String> isNotEmpty = isEmpty.negate();
Function 接口
Function 接口有一個參數並且返回一個結果,並附帶了一些可以和其他函數組合的默認方法(compose, andThen):
- Function<String, Integer> toInteger = Integer::valueOf;
- Function<String, String> backToString = toInteger.andThen(String::valueOf);
- backToString.apply(”123”); // “123”
Supplier 接口
Supplier 接口返回一個任意範型的值,和Function接口不同的是該接口沒有任何參數
- Supplier<Person> personSupplier = Person::new;
- personSupplier.get(); // new Person
Consumer 接口
Consumer 接口表示執行在單個參數上的操作。
- Consumer<Person> greeter = (p) -> System.out.println(“Hello, ” + p.firstName);
- greeter.accept(new Person(“Luke”, “Skywalker”));
Comparator 接口
Comparator 是老Java中的經典接口, Java 8在此之上添加了多種默認方法:
- Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
- Person p1 = new Person(“John”, “Doe”);
- Person p2 = new Person(“Alice”, “Wonderland”);
- comparator.compare(p1, p2); // > 0
- comparator.reversed().compare(p1, p2); // < 0
Optional 接口
Optional 不是函數是接口,這是個用來防止NullPointerException異常的輔助類型,這是下一屆中將要用到的重要概念,現在先簡單的看看這個接口能幹什麼:
Optional 被定義爲一個簡單的容器,其值可能是null或者不是null。在Java 8之前一般某個函數應該返回非空對象但是偶爾卻可能返回了null,而在Java 8中,不推薦你返回null而是返回Optional。
- Optional<String> optional = Optional.of(“bam”);
- optional.isPresent(); // true
- optional.get(); // “bam”
- optional.orElse(”fallback”); // “bam”
- optional.ifPresent((s) -> System.out.println(s.charAt(0))); // “b”
Stream 接口
java.util.Stream 表示能應用在一組元素上一次執行的操作序列。Stream 操作分爲中間操作或者最終操作兩種,最終操作返回一特定類型的計算結果,而中間操作返回Stream本身,這樣你就可以將多個操作依次串起來。Stream 的創建需要指定一個數據源,比如 java.util.Collection的子類,List或者Set, Map不支持。Stream的操作可以串行執行或者並行執行。
首先看看Stream是怎麼用,首先創建實例代碼的用到的數據List:
- List<String> stringCollection = new ArrayList<>();
- stringCollection.add(”ddd2”);
- stringCollection.add(”aaa2”);
- stringCollection.add(”bbb1”);
- stringCollection.add(”aaa1”);
- stringCollection.add(”bbb3”);
- stringCollection.add(”ccc”);
- stringCollection.add(”bbb2”);
- stringCollection.add(”ddd1”);
Java 8擴展了集合類,可以通過 Collection.stream() 或者 Collection.parallelStream() 來創建一個Stream。下面幾節將詳細解釋常用的Stream操作:
Filter 過濾
過濾通過一個predicate接口來過濾並只保留符合條件的元素,該操作屬於中間操作,所以我們可以在過濾後的結果來應用其他Stream操作(比如forEach)。forEach需要一個函數來對過濾後的元素依次執行。forEach是一個最終操作,所以我們不能在forEach之後來執行其他Stream操作。
- stringCollection
- .stream()
- .filter((s) -> s.startsWith(”a”))
- .forEach(System.out::println);
- // “aaa2”, “aaa1”
Sort 排序
排序是一箇中間操作,返回的是排序好後的Stream。如果你不指定一個自定義的Comparator則會使用默認排序。
- stringCollection
- .stream()
- .sorted()
- .filter((s) -> s.startsWith(”a”))
- .forEach(System.out::println);
- // “aaa1”, “aaa2”
需要注意的是,排序只創建了一個排列好後的Stream,而不會影響原有的數據源,排序之後原數據stringCollection是不會被修改的:
- System.out.println(stringCollection);
- // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1
Map 映射
中間操作map會將元素根據指定的Function接口來依次將元素轉成另外的對象,下面的示例展示了將字符串轉換爲大寫字符串。你也可以通過map來講對象轉換成其他類型,map返回的Stream類型是根據你map傳遞進去的函數的返回值決定的。
- stringCollection
- .stream()
- .map(String::toUpperCase)
- .sorted((a, b) -> b.compareTo(a))
- .forEach(System.out::println);
- // “DDD2”, “DDD1”, “CCC”, “BBB3”, “BBB2”, “AAA2”, “AAA1”
Match 匹配
Stream提供了多種匹配操作,允許檢測指定的Predicate是否匹配整個Stream。所有的匹配操作都是最終操作,並返回一個boolean類型的值。
- boolean anyStartsWithA =
- stringCollection
- .stream()
- .anyMatch((s) -> s.startsWith(”a”));
- System.out.println(anyStartsWithA); // true
- boolean allStartsWithA =
- stringCollection
- .stream()
- .allMatch((s) -> s.startsWith(”a”));
- System.out.println(allStartsWithA); // false
- boolean noneStartsWithZ =
- stringCollection
- .stream()
- .noneMatch((s) -> s.startsWith(”z”));
- System.out.println(noneStartsWithZ); // true
Count 計數
計數是一個最終操作,返回Stream中元素的個數,返回值類型是long。
- long startsWithB =
- stringCollection
- .stream()
- .filter((s) -> s.startsWith(”b”))
- .count();
- System.out.println(startsWithB); // 3
Reduce 規約
這是一個最終操作,允許通過指定的函數來講stream中的多個元素規約爲一個元素,規越後的結果是通過Optional接口表示的:
- Optional<String> reduced =
- stringCollection
- .stream()
- .sorted()
- .reduce((s1, s2) -> s1 + ”#” + s2);
- reduced.ifPresent(System.out::println);
- // “aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2”
並行Streams
前面提到過Stream有串行和並行兩種,串行Stream上的操作是在一個線程中依次完成,而並行Stream則是在多個線程上同時執行。
下面的例子展示了是如何通過並行Stream來提升性能:
首先我們創建一個沒有重複元素的大表:
- int max = 1000000;
- List<String> values = new ArrayList<>(max);
- for (int i = 0; i < max; i++) {
- UUID uuid = UUID.randomUUID();
- values.add(uuid.toString());
- }
然後我們計算一下排序這個Stream要耗時多久,
串行排序:
- long t0 = System.nanoTime();
- long count = values.stream().sorted().count();
- System.out.println(count);
- long t1 = System.nanoTime();
- long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
- System.out.println(String.format(”sequential sort took: %d ms”, millis));
// 串行耗時: 899 ms
並行排序:
- long t0 = System.nanoTime();
- long count = values.parallelStream().sorted().count();
- System.out.println(count);
- long t1 = System.nanoTime();
- long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
- System.out.println(String.format(”parallel sort took: %d ms”, millis));
// 並行排序耗時: 472 ms
上面兩個代碼幾乎是一樣的,但是並行版的快了50%之多,唯一需要做的改動就是將stream()改爲parallelStream()。
Map
前面提到過,Map類型不支持stream,不過Map提供了一些新的有用的方法來處理一些日常任務。
- Map<Integer, String> map = new HashMap<>();
- for (int i = 0; i < 10; i++) {
- map.putIfAbsent(i, ”val” + i);
- }
map.forEach((id, val) -> System.out.println(val));
以上代碼很容易理解, putIfAbsent 不需要我們做額外的存在性檢查,而forEach則接收一個Consumer接口來對map裏的每一個鍵值對進行操作。
- map.computeIfPresent(3, (num, val) -> val + num);
- map.get(3); // val33
- map.computeIfPresent(9, (num, val) -> null);
- map.containsKey(9); // false
- map.computeIfAbsent(23, num -> “val” + num);
- map.containsKey(23); // true
- map.computeIfAbsent(3, num -> “bam”);
- map.get(3); // val33
接下來展示如何在Map裏刪除一個鍵值全都匹配的項:
- map.remove(3, “val3”);
- map.get(3); // val33
- map.remove(3, “val33”);
- map.get(3); // null
另外一個有用的方法:
- map.getOrDefault(42, “not found”); // not found
對Map的元素做合併也變得很容易了:
- map.merge(9, “val9”, (value, newValue) -> value.concat(newValue));
- map.get(9); // val9
- map.merge(9, “concat”, (value, newValue) -> value.concat(newValue));
- map.get(9); // val9concat
Merge做的事情是如果鍵名不存在則插入,否則則對原鍵對應的值做合併操作並重新插入到map中。
九、Date API
Java 8 在包java.time下包含了一組全新的時間日期API。新的日期API和開源的Joda-Time庫差不多,但又不完全一樣,下面的例子展示了這組新API裏最重要的一些部分:
Clock 時鐘
Clock類提供了訪問當前日期和時間的方法,Clock是時區敏感的,可以用來取代 System.currentTimeMillis() 來獲取當前的微秒數。某一個特定的時間點也可以使用Instant類來表示,Instant類也可以用來創建老的java.util.Date對象。
- Clock clock = Clock.systemDefaultZone();
- long millis = clock.millis();
- Instant instant = clock.instant();
- Date legacyDate = Date.from(instant); // legacy java.util.Date
Timezones 時區
在新API中時區使用ZoneId來表示。時區可以很方便的使用靜態方法of來獲取到。 時區定義了到UTS時間的時間差,在Instant時間點對象到本地日期對象之間轉換的時候是極其重要的。
- System.out.println(ZoneId.getAvailableZoneIds());
- // prints all available timezone ids
- ZoneId zone1 = ZoneId.of(”Europe/Berlin”);
- ZoneId zone2 = ZoneId.of(”Brazil/East”);
- System.out.println(zone1.getRules());
- System.out.println(zone2.getRules());
- // ZoneRules[currentStandardOffset=+01:00]
- // ZoneRules[currentStandardOffset=-03:00]
LocalTime 本地時間
LocalTime 定義了一個沒有時區信息的時間,例如 晚上10點,或者 17:30:15。下面的例子使用前面代碼創建的時區創建了兩個本地時間。之後比較時間並以小時和分鐘爲單位計算兩個時間的時間差:
- LocalTime now1 = LocalTime.now(zone1);
- LocalTime now2 = LocalTime.now(zone2);
- System.out.println(now1.isBefore(now2)); // false
- long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
- long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
- System.out.println(hoursBetween); // -3
- System.out.println(minutesBetween); // -239
LocalTime 提供了多種工廠方法來簡化對象的創建,包括解析時間字符串。
- LocalTime late = LocalTime.of(23, 59, 59);
- System.out.println(late); // 23:59:59
- DateTimeFormatter germanFormatter =
- DateTimeFormatter
- .ofLocalizedTime(FormatStyle.SHORT)
- .withLocale(Locale.GERMAN);
- LocalTime leetTime = LocalTime.parse(”13:37”, germanFormatter);
- System.out.println(leetTime); // 13:37
LocalDate 本地日期
LocalDate 表示了一個確切的日期,比如 2014-03-11。該對象值是不可變的,用起來和LocalTime基本一致。下面的例子展示瞭如何給Date對象加減天/月/年。另外要注意的是這些對象是不可變的,操作返回的總是一個新實例。
- LocalDate today = LocalDate.now();
- LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
- LocalDate yesterday = tomorrow.minusDays(2);
- LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
- DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek); // FRIDAY
從字符串解析一個LocalDate類型和解析LocalTime一樣簡單:
- DateTimeFormatter germanFormatter =
- DateTimeFormatter
- .ofLocalizedDate(FormatStyle.MEDIUM)
- .withLocale(Locale.GERMAN);
- LocalDate xmas = LocalDate.parse(”24.12.2014”, germanFormatter);
- System.out.println(xmas); // 2014-12-24
LocalDateTime 本地日期時間
LocalDateTime 同時表示了時間和日期,相當於前兩節內容合併到一個對象上了。LocalDateTime和LocalTime還有LocalDate一樣,都是不可變的。LocalDateTime提供了一些能訪問具體字段的方法。
- LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
- DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
- System.out.println(dayOfWeek); // WEDNESDAY
- Month month = sylvester.getMonth();
- System.out.println(month); // DECEMBER
- long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
- System.out.println(minuteOfDay); // 1439
只要附加上時區信息,就可以將其轉換爲一個時間點Instant對象,Instant時間點對象可以很容易的轉換爲老式的java.util.Date。
- Instant instant = sylvester
- .atZone(ZoneId.systemDefault())
- .toInstant();
- Date legacyDate = Date.from(instant);
- System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014
格式化LocalDateTime和格式化時間和日期一樣的,除了使用預定義好的格式外,我們也可以自己定義格式:
- DateTimeFormatter formatter =
- DateTimeFormatter
- .ofPattern(”MMM dd, yyyy - HH:mm”);
- LocalDateTime parsed = LocalDateTime.parse(”Nov 03, 2014 - 07:13”, formatter);
- String string = formatter.format(parsed);
- System.out.println(string); // Nov 03, 2014 - 07:13
和java.text.NumberFormat不一樣的是新版的DateTimeFormatter是不可變的,所以它是線程安全的。
關於時間日期格式的詳細信息:http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html
十、Annotation 註解
在Java 8中支持多重註解了,先看個例子來理解一下是什麼意思。
首先定義一個包裝類Hints註解用來放置一組具體的Hint註解:
- @interface Hints {
- Hint[] value();
- }
- @Repeatable(Hints.class)
- @interface Hint {
- String value();
- }
Java 8允許我們把同一個類型的註解使用多次,只需要給該註解標註一下@Repeatable即可。例 1: 使用包裝類當容器來存多個註解(老方法)
- @Hints({@Hint(“hint1”), @Hint(“hint2”)})
- class Person {}
例 2:使用多重註解(新方法)
- @Hint(“hint1”)
- @Hint(“hint2”)
- class Person {}
第二個例子裏java編譯器會隱性的幫你定義好@Hints註解,瞭解這一點有助於你用反射來獲取這些信息:
- Hint hint = Person.class.getAnnotation(Hint.class);
- System.out.println(hint); // null
- Hints hints1 = Person.class.getAnnotation(Hints.class);
- System.out.println(hints1.value().length); // 2
- Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
- System.out.println(hints2.length); // 2
即便我們沒有在Person類上定義@Hints註解,我們還是可以通過 getAnnotation(Hints.class) 來獲取 @Hints註解,更加方便的方法是使用 getAnnotationsByType 可以直接獲取到所有的@Hint註解。
另外Java 8的註解還增加到兩種新的target上了:
- @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
- @interface MyAnnotation {}
關於Java 8的新特性就寫到這了,肯定還有更多的特性等待發掘。JDK 1.8裏還有很多很有用的東西,比如Arrays.parallelSort, StampedLock和CompletableFuture等等。