I want to fly higher
programming Explorer
posts - 114,comments - 263,trackbacks - 0
    本篇用代码示例结合JDk源码及本人的理解讲了Java8新的时间API以及Repeatable Annotation.       
     参考:http://winterbe.com/posts/2014/03/16/java-8-tutorial/

    1.java.time API

package com.mavsplus.java8.turtorial.time;

import java.time.Clock;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;
import java.util.Set;

/**
 * Java 8 包含了全新的时间日期API,这些功能都放在了java.time包下。新的时间日期API是基于Joda-Time库开发的,但是也不尽相同
 * 
 * <p>
 * public abstract class Clock {
 * 
 * @author landon
 * @since 1.8.0_25
 
*/

public class TimeAPIExample {

    
/**
     * Clock提供了对当前时间和日期的访问功能。Clock是对当前时区敏感的,并可用于替代System.currentTimeMillis()
     * 方法来获取当前的毫秒时间。当前时间线上的时刻可以用Instance类来表示。Instance也能够用于创建原先的java.util.Date对象。
     
*/

    
public void useClock() {
        Clock clock = Clock.systemDefaultZone();

        
long clockMillis = clock.millis();
        
long curMillis = System.currentTimeMillis();

        
// %d格式包括了int/long等
        
// 从输出可以看出,二者完全相同
        System.out.format("clockMillis:%d,curMillis:%d", clockMillis, curMillis).println();

        Instant instant = clock.instant();
        
// 这里lagacy可以理解为传统的
        Date legacyDate = Date.from(instant);

        System.out.println(String.format("legacyDate:%d", legacyDate.getTime()));
    }


    
/**
     * 时区类可以用一个ZoneId来表示。时区类的对象可以通过静态工厂方法方便地获取。时区类还定义了一个偏移量,
     * 用来在当前时刻或某时间与目标时区时间之间进行转换
     
*/

    
public void useTimeZone() {
        
// public abstract class ZoneId implements Serializable

        
// 迭代可用的时区
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        
// 现学现卖!lambda!
        availableZoneIds.stream().forEach(System.out::println);

        ZoneId zoneId1 = ZoneId.of("Asia/Shanghai");
        ZoneId zoneId2 = ZoneId.of("America/New_York");

        
// 输出:ZoneRules[currentStandardOffset=+08:00]
        System.out.println(zoneId1.getRules());
        
// 输出:ZoneRules[currentStandardOffset=-05:00]
        System.out.println(zoneId2.getRules());
    }


    
/**
     * 本地时间类表示一个没有指定时区的时间,例如,10
     * p.m.或者17:30:15,下面的例子会用上面的例子定义的时区创建两个本地时间对象。然后我们会比较两个时间,并计算它们之间的小时和分钟的不同
     * 
     * LocalTime是由多个工厂方法组成,其目的是为了简化对时间对象实例的创建和操作,包括对时间字符串进行解析的操作
     
*/

    
public void useLocalTime() {
        ZoneId zoneId1 = ZoneId.of("Asia/Shanghai");
        ZoneId zoneId2 = ZoneId.of("America/New_York");

        LocalTime now1 = LocalTime.now(zoneId1);
        LocalTime now2 = LocalTime.now(zoneId2);

        System.out.println(now1.isBefore(now2));
        System.out.println(now1.isAfter(now2));

        
// public enum ChronoUnit implements TemporalUnit
        
// Chrono_计时器
        long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
        
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);

        
// 因为一个是s+8,一个是s-5,相差13个小时
        System.out.println(hoursBetween);
        System.out.println(minutesBetween);

        LocalTime lt = LocalTime.of(161915);
        System.out.println(lt);

        
// public final class DateTimeFormatter
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(
                Locale.SIMPLIFIED_CHINESE);
        
// 注意这里必须要用"下午6:30"(或者上午),因为Locale选择的是中国,否则其他形式报错
        LocalTime lt2 = LocalTime.parse("下午6:30", formatter);
        
// 输出:18:30
        System.out.println(lt2);
    }


    
/**
     * 本地日期表示了一个独一无二的时间,例如:2014-03-11。这个时间是不可变的,与LocalTime是同源的。下面的例子演示了如何通过加减日,月
     * , 年等指标来计算新的日期。记住,每一次操作都会返回一个新的时间对象
     * 
     * 解析字符串并形成LocalDate对象,这个操作和解析LocalTime一样简单
     
*/

    
public void useLocalDate() {
        LocalDate today = LocalDate.now();
        
// 输出:2014-11-19
        System.out.println(today);

        
// 获取明天
        LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
        
// 获取昨天
        LocalDate yesterday = tomorrow.minusDays(2);

        System.out.println(String.format("tomorrow:%s,yesterday:%s", tomorrow, yesterday));

        
// 国庆节
        LocalDate nationalDay = LocalDate.of(2014, Month.OCTOBER, 1);
        DayOfWeek dayOfWeek = nationalDay.getDayOfWeek();

        
// 2014年10月1是星期三
        
// 输出:WEDNESDAY
        System.out.println(dayOfWeek);

        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(
                Locale.SIMPLIFIED_CHINESE);
        
// 注意这里第一个参数文本"2014-11-19",目前测试必须这样,因为Locale为中国
        LocalDate ld = LocalDate.parse("2014-11-19", formatter);

        System.out.println(ld);
    }


    
/**
     * LocalDateTime表示的是日期-时间。它将刚才介绍的日期对象和时间对象结合起来,形成了一个对象实例。LocalDateTime是不可变的,
     * 与LocalTime和LocalDate的工作原理相同。我们可以通过调用方法来获取日期时间对象中特定的数据域
     
*/

    
public void useLocalDateTime() {
        LocalDateTime end2014 = LocalDateTime.of(2014, Month.DECEMBER, 31235959);

        
// 2014年12月31日是星期三
        DayOfWeek dayOfWeek = end2014.getDayOfWeek();
        
// 输出:WEDNESDAY
        System.out.println(dayOfWeek);

        Month month = end2014.getMonth();
        
// 输出:DECEMBER
        System.out.println(month);

        
// This counts the minute within the day(23 * 60 + 59 = 1439)
        long minuteOfDay = end2014.getLong(ChronoField.MINUTE_OF_DAY);
        
// 输出:1439
        System.out.println(minuteOfDay);

        
// 如果再加上的时区信息,LocalDateTime能够被转换成Instance实例。Instance能够被转换成以前的java.util.Date对象
        Instant instant = end2014.atZone(ZoneId.systemDefault()).toInstant();
        Date legacyDate = Date.from(instant);

        
// 输出:Wed Dec 31 23:59:59 CST 2014
        System.out.println(legacyDate);

        
// 格式化日期-时间对象就和格式化日期对象或者时间对象一样。除了使用预定义的格式以外,我们还可以创建自定义的格式化对象,然后匹配我们自定义的格式。
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy,MM-dd HH:mm");
        LocalDateTime parsed = LocalDateTime.parse("2014,11-19 19:23", formatter);

        System.out.println(formatter.format(parsed));

        
// 不同于java.text.NumberFormat,新的DateTimeFormatter类是不可变的,也是线程安全的
        
// ->因为public final class DateTimeFormatter->final的
    }


    
public static void main(String[] args) {
        TimeAPIExample example = new TimeAPIExample();

        example.useClock();
        example.useTimeZone();
        example.useLocalTime();
        example.useLocalDate();
        example.useLocalDateTime();
    }

}



    2.Repeatable Annotation

package com.mavsplus.java8.turtorial.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotations in Java 8 are repeatable
 * 
 * @author landon
 * @since 1.8.0_25
 
*/

public class AnnotationRepeatableExample {

    
// 包装注解,其包括了Hint的数组
    
// 这里必须加上@Retention(RetentionPolicy.RUNTIME),因为运行时反射要读取该信息
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    
public @interface Hints {
        Hint[] value();
    }


    
/**
     * <code>
     * 
     * @Documented
     * @Retention(RetentionPolicy.RUNTIME)
     * @Target(ElementType.ANNOTATION_TYPE) public @interface Repeatable {
     *                                      Class<? extends Annotation> value();
     *                                      } </code>
     *
     
*/


    
// 实际的注解
    
// 这里必须加上@Retention(RetentionPolicy.RUNTIME),因为运行时反射要读取该信息
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Repeatable(Hints.class)
    
public @interface Hint {
        String str();
    }


    
// 老办法
    @Hints({ @Hint(str = "hint1"), @Hint(str = "hint2") })
    
public class Bean {
    }


    
// 新方法,使用可重复注解

    
// 如果Hint注解没有加上Repetable则会编译错误
    
// Only annotation types marked @Repeatable can be used multiple times at
    
// one target.
    @Hint(str = "hint1")
    @Hint(str = "hint2")
    
public class Bean2 {
    }


    
// 使用变体2,Java编译器能够在内部自动对@Hint进行设置
    public void reflectAnnotation() throws Exception {
        Hint hint = Bean2.class.getAnnotation(Hint.class);
        
// 输出null
        System.out.println(hint);

        
// 注意这里是$Bean
        Hints hints3 = Class.forName("com.mavsplus.java8.turtorial.annotation.AnnotationRepeatableExample$Bean")
                .getAnnotation(Hints.class);
        
// 输出2
        System.out.println(hints3.value().length);

        Hints hints4 = Bean.class.getAnnotation(Hints.class);
        
// 输出2
        System.out.println(hints4.value().length);

        
// 这里传入Hints.class依然可以获取注解信息(因为Hint上有@Repeatable(Hints.class)这个注解)
        
// 尽管我们没有在Bean2类上声明@Hints注解,但是它的信息仍然可以通过getAnnotation(Hints.class)来读取
        Hints hints1 = Bean2.class.getAnnotation(Hints.class);
        
// 输出2
        System.out.println(hints1.value().length);

        
// getAnnotationsByType方法会更方便,因为它赋予了所有@Hint注解标注的方法直接的访问权限。
        
// 看一下这段注释:
        
// The difference between this method and getAnnotation(Class)
        
// is that this method detects if its argument is a repeatable
        
// annotation type (JLS 9.6), and if so, attempts to find one or more
        
// annotations of that type by "looking through" a container annotation
        Hint[] hints2 = Bean2.class.getAnnotationsByType(Hint.class);
        
// 输出2
        System.out.println(hints2.length);
    }


    
public static void main(String[] args) throws Exception {
        AnnotationRepeatableExample example = new AnnotationRepeatableExample();

        example.reflectAnnotation();
    }

}



package com.mavsplus.java8.turtorial.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 和AnnotationRepeatableExample对比的一个例子
 * 
 * @author landon
 * @since 1.8.0_25
 
*/

public class AnnotationExample {

    
// 经测试发现,这段代码要通过编译, WrappedAnno中的方法名必须为value.
    
// 同时参考了@Target源代码以及@Retention源代码,发现方法命名也为value.

    
// 解释(by landon)
    
// 1.个人认为注解内部方法返回值如果为数组的话,如果方法名为value的话,可以不用写类似于Anno(xxx =
    
// {}),可直接写Anno({}),参见AnnoModified2
    
// 2.其实不一定返回值为数组,只要方法名定义为value的话,则赋值的话均无须指明value=xxx,参见AnnoModified3

    
// 总结:编译器默认注解内部方法名为value. 注:当且仅当注解内部只有一个方法时可以这样,参见AnnoModified4

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface WrappedAnno {
        Anno[] value();
    }


    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @interface Anno {
        String name();

        
int num();
    }


    @WrappedAnno({ @Anno(name = "value1", num = 1), @Anno(name = "value2", num = 2) })
    
class AnnoModified {
    }


    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @
interface WrappedAnno2 {
        String[] values();
    }


    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @
interface WrappedAnno3 {
        
int value();
    }


    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @
interface WrappedAnno4 {
        
int value();

        String name();
    }


    @WrappedAnno2(values 
= "HI""Anno" })
    
class AnnoModified2 {
    }


    @WrappedAnno3(
2)
    
class AnnoModified3 {
    }


    @WrappedAnno4(value 
= 4, name = "Anno")
    
class AnnoModified4 {
    }

}


posted on 2014-11-20 14:37 landon 阅读(5615) 评论(0)  编辑  收藏 所属分类: Program

只有注册用户登录后才能发表评论。


网站导航: