Java8特性总结(三)接口方法,注解,日期,Base64

导航

Java8特性总结(一)概述
Java8特性总结(二)Lambda表达式,函数式接口,方法引用
Java8特性总结(三)接口方法,注解,日期,Base64

前言

这几个知识点相对内容较少,放到一篇文章里介绍。

接口方法

接口方法如何写,大家都知道了,很简单。
谈到接口方法,那就难免不谈谈他的继承关系。

多个接口

Java是可以实现多个接口的,那这个时候实现的多个接口有同名,同参的接口方法会发生什么情况呢。
接下来我们就通过代码示例,展开分析一下。

接口IA,
两个子接口IB1,IB2,
实现了IB1和IB2的类CC,
继承了IB1,IB2的接口IC, 大致就是3层关系。

代码:

public interface IA
{
    default void print(String str)
    {
        System.out.println(this.getClass()+".print() IA "+str);
    }
}

public interface IB1 extends IA
{
}

public interface IB2 extends IA
{
}

public interface IC extends IB1,IB2
{   
}

public class C implements IB1, IB2
{
    public static void main(String[] args)
    {
        new C().print("test");

    }
}

1:IA的默认方法print(),IB1,IB2没有Override print().
这种情况一切正常,没有任何问题,最后执行C的输出是:

class my.test.java8.second.interfaceMethod1.C.print() IA test

2:IA定义默认方法print(),IB1 Override了print().

public interface IB1 extends IA
{
    default void print(String str)
    {
        System.out.println(this.getClass()+".print() IB1 "+str);
    }
}

这种情况也是正常,编译器也没有报任何错误,最后是C的输出

class my.test.java8.second.interfaceMethod1.C.print() IB1 test

发现输出调用的是IB1的默认方法。

可以得出结论,实现类只在乎离自己最近的那个接口的默认方法。

3:IA定义了默认方法print(),IB1和IB2分别Override。

public interface IB2 extends IA
{
    default void print(String str)
    {
        System.out.println(this.getClass()+".print() IB2 "+str);
    }
}

出事了,IC和C都报错了,因为编译器已经混乱了,不知道该调用IB1的方法还是IB2的方法。
Java给出的解决问题的办法就是每个子类Override这个方法,告诉编译器,我不调用别人的,我调用我自己的方法。

为C类添加函数,类似的也给IC添加。

@Override
public void print(String str)
{
    IB1.super.print(str);
    IB2.super.print(str);
}

编译过去了,看看输出吧

class my.test.java8.second.interfaceMethod1.C.print() IB1 test
class my.test.java8.second.interfaceMethod1.C.print() IB2 test

我们分别调用了两个父接口的默认方法。
当然我们也可以在方法中自己实现。

父类和接口

接下来就是继承类,实现接口,接口和类有同名,同参函数的情况了。

接口IA;
类CA;
抽象类ACA;
类CB1继承CA,实现IA;
类CB2继承ACA,实现IA。

public interface IA
{
    default void print(String str)
    {
        System.out.println(this.getClass()+".print() IA  "+str);
    }
}
public class CA
{
    public void print(String str)
    {
        System.out.println(this.getClass()+".print() CA  "+str);
    }
}
public abstract class ACA
{
    public abstract void print(String str);
}
public class CB1 extends CA implements IA
{
    public static void main(String[] args)
    {
        new CB1().print("hello");
    }
}
public class CB2 extends ACA implements IA
{

}

CB2直接报错。必须要Override print()方法。
修改CB2

public class CB2 extends ACA implements IA
{

    @Override
    public void print(String str)
    {       
    }
}

运行CB1.输出如下

class my.test.java8.second.interfaceMethod2.CB1.print() CA  hello

调用的是父类的方法。

可以得出结论,父类的方法优先于接口。

注解的变化

注解的变化还是比较小,增加了可以反复添加注解的功能。
通过代码来看看如何实现。
在一个注解中使用另外一个注解数组,这个以前版本是支持的

@Retention(RetentionPolicy.RUNTIME)
public @interface Student
{
    String value();
}

@Retention(RetentionPolicy.RUNTIME)
public @interface Classes
{
    Student[] value();
}

实际使用情况

@Classes({@Student("李壮"),@Student("王静")})
public class MyClasses
{

}

现在的版本可以写成这样。和上面的写法是等价的。

@Student("李壮")
@Student("王静")
public class MyClasses
{

}

编译器报错了!提示我们@Student不是一个repeatabel的注解。
@Repeatable这个注解的注释说的很清楚,value必须是当前注解的注解集合。
如下所示:

@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Classes.class)
public @interface Student
{
    String value();
}

改成这样错误消失。

打印测试一下结果。

public static void main(String[] args)
{
    Student student=MyClasses.class.getAnnotation(Student.class);
    System.out.println(student);

    Student[] students=MyClasses.class.getAnnotationsByType(Student.class);
    Arrays.asList(students).stream().forEach(e->System.out.println(e.value()));

    Classes classes=MyClasses.class.getDeclaredAnnotation(Classes.class);
    Arrays.asList(classes.value()).stream().forEach(e->System.out.println(e.value()));

}    

可以看出现在这种重复的注解方式,实际上是隐式的包装成Classes。
这个知识点使用较少,也就Mark一下,以备不时之需。

Base64

Base64编码引入了标准包里,使用更方便了。
以前版本使用Base64一般会用第三方的类。
比如我常用apache 的 commmon-codec.jar里Base64进行编码和解码。

String base64String = "I am  base64";  
byte[] result = Base64.encodeBase64(base64String.getBytes());

当然还有一些其他的。
现在直接使用Java自己的,而且据说也是效率最高的。

import java.util.Base64;

public class Base64Test
{

    public static void main(String[] args) throws Exception
    {
        String base64String = "I am  base64";  
        String encoded=Base64.getEncoder().encodeToString(base64String.getBytes("UTF-8"));
        String end=new String(Base64.getDecoder().decode(encoded),"UTF-8");
        System.out.println(encoded);
        System.out.println(end);
    }

}

日期

新的时间变化包括有。
LocalDate,LocalTime,LocalDateTime,Clock,时区的概念,时间差的概念。

LocalDate

public class LocalDateTest
{

    public static void main(String[] args)
    {
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
        LocalDate yesterday = tomorrow.minusDays(2);
        System.out.println(tomorrow);
        System.out.println(yesterday);

        LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
        DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
        System.out.println(dayOfWeek); // FRIDAY
    }

}   

输出结果

2017-01-20
2017-01-18
FRIDAY

直观的感觉运算比以前简单了不少。

LocalTime

public class LocalTimeTest
{

    public static void main(String[] args)
    {

        LocalTime time=LocalTime.now();
        System.out.println(time);
        System.out.println(time.minusHours(1));
        System.out.println(time.minusMinutes(10));
        System.out.println(time.plusHours(10));
        LocalTime late = LocalTime.of(23, 59, 59);
        System.out.println(late); // 23:59:59       
    }
}

输出结果

14:22:14.033
13:22:14.033
14:12:14.033
00:22:14.033
23:59:59

感觉运算好方便。

LocalDateTime

public class LocalDateTimeTest
{

    public static void main(String[] args)
    {
        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

        LocalDateTime localdt=LocalDateTime.now();
        System.out.println(localdt);

    }

}

输出结果

WEDNESDAY
DECEMBER
1439
2017-01-19T14:23:34.938

ZoneId时区

public class TimeZoneTest
{
    public static void main(String[] args)
    {
        //打印所有的时区
        System.out.println(ZoneId.getAvailableZoneIds());

        ZoneId zone1 = ZoneId.of("Europe/Berlin");
        ZoneId zone2 = ZoneId.of("Brazil/East");
        ZoneId zone3=ZoneId.of("Asia/Shanghai");
        System.out.println(zone1.getRules());
        System.out.println(zone2.getRules());
        System.out.println(zone3.getRules());

        LocalTime now2 = LocalTime.now(zone2);
        LocalTime now1 = LocalTime.now(zone1);      

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

        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

    }
}

打印结果

[Asia/Aden, America/Cuiaba, 。。。。。 Europe/Monaco]//太长了
ZoneRules[currentStandardOffset=+01:00]东一区
ZoneRules[currentStandardOffset=-03:00]西三区
ZoneRules[currentStandardOffset=+08:00]东八区
07:24:39.798
04:24:39.798
false
-3
-180

Clock

public class ClockTest
{
    public static void main(String[] args)
    {
        Clock clock = Clock.systemDefaultZone();
        long millis = clock.millis();
        System.out.println(millis);

        Instant instant = clock.instant();
        Date legacyDate = Date.from(instant);   // legacy java.util.Date
        System.out.println(legacyDate);
    }
}

输出

1484807586661
Thu Jan 19 14:33:06 CST 2017

和当前日期类型的转换关系,获取当前时区时间的毫秒。

Duration

public class DurationTest
{
    public static void main(String[] args)
    {
        final LocalDateTime from = LocalDateTime.of( 2014, Month.MARCH, 16, 0, 0, 0 );
        final LocalDateTime to = LocalDateTime.now();

    final Duration duration = Duration.between( from, to );
    System.out.println( "Duration in days: " + duration.toDays() );
    System.out.println( "Duration in hours: " + duration.toHours() );
    }

}

输出

Duration in days: 1040
Duration in hours: 24974

参考文章
http://www.cnblogs.com/guangshan/p/4889732.html
http://blog.csdn.net/calmspeed/article/details/44995105
http://www.importnew.com/11908.html
http://ifeve.com/java-8-tutorial-2/
http://www.importnew.com/15637.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值