java7或java8新特性

本文介绍了Java 7和Java 8的主要新特性,包括:数值类型字面值分隔增强可读性,字符串在switch语句中的应用,接口的static方法和默认实现,带资源的try语句,多重捕获异常,最后重新抛出异常,lambda表达式的引入,@FunctionalInterface注解,以及类型注解的扩展。这些特性提升了Java的可读性和编程效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

技术交流qq群: 659201069

1、jdk7,数值类型字面值可以用‘多个‘—’分隔增加可读性

        int a = 123_456;
        double b = 123_456e3;

2、jdk7,可以使用字符串控制switch语句

        String str = "abc";
        switch (str){
            case "abc":
                System.out.println("abc");
                break;
            case "cef":
                System.out.println("abc");
                break;
            default:
                    System.out.println("null");

        }

3、jdk8、可以为接口添加static方法和默认实现

public interface searchService {
    public int search(String key);
    /**
     * jdk8新增特性,可以为接口中的方法定义默认实现
     *
     */

    default String get(String aa,String bb){
        System.out.println("我是jdk1.8默认实现方法...");
        return "";
    }

    String aa="2222";

    /**
     * jdk8新增特性,可以为接口添加static方法
     *
     */
    static void staticmethod(){System.out.println("我是静态方法"+aa);}
}

4、jdk7,带资源的try语句,当资源(例如文件)不再需要时能够自行释放

class ShowFile { 
  public static void main(String args[]) 
  { 
    int i; 

    // First, confirm that a file name has been specified. 
    if(args.length != 1) { 
      System.out.println("Usage: ShowFile filename"); 
      return; 
    } 

    // The following code uses a try-with-resources statement to open 
    // a file and then automatically close it when the try block is left. 
    try(FileInputStream fin = new FileInputStream(args[0])) {  

      do { 
        i = fin.read(); 
        if(i != -1) System.out.print((char) i); 
      } while(i != -1); 

    } catch(FileNotFoundException e) { 
      System.out.println("File Not Found."); 
    } catch(IOException e) { 
      System.out.println("An I/O Error Occurred"); 
    }  

  } 
}

5、jdk7,多重捕获异常(multi-catch),本来不同的异常是由多个catch语句块来处理,现在可以把多个异常用一个catch语句块来处理,用’|’来表示多个异常,也就是或的意思

class MultiCatch {
  public static void main(String args[]) {
    int a=10, b=0;
    int vals[] = { 1, 2, 3 };

    try {
      int result = a / b; // generate an ArithmeticException  

//      vals[10] = 19; // generate an ArrayIndexOutOfBoundsException

      // This catch clause catches both exceptions.
    } catch(ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println("Exception caught: " + e);
    }

    System.out.println("After multi-catch.");
  }
}

6、jdk7,最后重新抛出异常(final-rethrow),在rethrow方法中,catch块捕获的异常并没有出现在throws从句中。Java 7编译器会分析完整的try代码块以检查从catch块中什么类型的异常被抛出和重新抛出

public class ReThrowExceptions {

    public static void main(String[] args) {
        try{
            rethrow("abc");
        }catch(FirstException | SecondException | ThirdException e){
            //以下赋值将会在编译期抛出异常,因为e是final型的
            //e = new Exception();
            System.out.println(e.getMessage());
        }
    }

    static void rethrow(String s) throws FirstException, SecondException,
            ThirdException {
        try {
            if (s.equals("First"))
                throw new FirstException("First");
            else if (s.equals("Second"))
                throw new SecondException("Second");
            else
                throw new ThirdException("Third");
        } catch (Exception e) {
            //下面的赋值没有启用重新抛出异常的类型检查功能,这是Java 7的新特性
            // e=new ThirdException();
            throw e;
        }
    }

    static class FirstException extends Exception {

        public FirstException(String msg) {
            super(msg);
        }
    }

    static class SecondException extends Exception {

        public SecondException(String msg) {
            super(msg);
        }
    }

    static class ThirdException extends Exception {

        public ThirdException(String msg) {
            super(msg);
        }
    }

}

7、jdk8,lambda表达式,函数式编程

/**用lambda表达式实现Runnable
// Java 8之前:
new Thread(new Runnable() {
    @Override
    public void run() {
    System.out.println("Before Java8, too much code for too little to do");
    }
}).start();


//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
// Java 8,lambda实现迭代:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));

8、jdk8,新增@FunctionalInterface注解,属于标记注解,用来标记被注解的接口是函数式接口。如果被注解的接口不是函数式接口,编译将报错。但是创建函数式接口并不需要@FunctionalInterface,这个注解只是用来提供信息,也就是更显法的说明此接口是函数式接口。根据java8的定义任何只有一个抽像方法的接口都是函数式接口(可以包括其它变量成员和方法,只要抽像方法是一个就可以),没有@FunctionalInterface注解,也是函数式接口。例如java8内置的Runnable接口,使用了@FunctionalInterface注解,显示说明Runnable是函数式接口,但完全可以不用这个注解,Runnable也是函数式接口。例如下面自定义的TestInterface接口,只有一个抽像方法本身就是函数式接口,与@FunctionalInterface没有任何关系,这个注解只是用来提供信息的,显示的标明这是一个函数式接口而式。

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
@FunctionalInterface
public interface TestInterface {
    // 抽象方法
    public void sub();
    // java.lang.Object中的方法不是抽象方法
    public boolean equals(Object var1);
    // default不是抽象方法
    public default void defaultMethod(){

    }
    // static不是抽象方法
    public static void staticMethod(){

    }
}

9、jdk8,增加了类型注解,在之前注解只能用于声明,也就是方法、变量、类、接口声明的地方,java8开始在很多使用类型的其它地方也可以使用注解,例如方法返回类型、throws子句等。下面看官方给出的例子,在大多数类型前面都可以使用注解

// Use an annotation on a type parameter.
class TypeAnnoDemo<@What(description = "Generic data type") T> {

    // Use a type annotation on a constructor.
    public @Unique TypeAnnoDemo() {}

    // Annotate the type (in this case String), not the field.
    @TypeAnno String str;

    // This annotates the field test.
    @EmptyOK String test;

    // Use a type annotation to annotate this (the receiver).
    public int f(@TypeAnno TypeAnnoDemo<T> this, int x) {
        return 10;
    }

    // Annotate the return type.
    public @TypeAnno Integer f2(int j, int k) {
        return j+k;
    }

    // Annotate the method declaration.
    public @Recommended Integer f3(String str) {
        return str.length() / 2;
    }

    // Use a type annotation with a throws clause.
    public void f4() throws @TypeAnno NullPointerException {
        // ...
    }

    // Annotate array levels.
    String @MaxLen(10) [] @NotZeroLen [] w;

    // Annotate the array element type.
    @TypeAnno Integer[] vec;

    public static void myMeth(int i) {

        // Use a type annotation on a type argument.
        TypeAnnoDemo<@TypeAnno Integer> ob =
                new TypeAnnoDemo<@TypeAnno Integer>();

        // Use a type annotation with new.
        @Unique TypeAnnoDemo<Integer> ob2 = new @Unique TypeAnnoDemo<Integer>();

        Object x = new Integer(10);
        Integer y;

        // Use a type annotation on a cast.
        y = (@TypeAnno Integer) x;
    }

    public static void main(String args[]) {
        myMeth(10);
    }

    // Use type annotation with inheritance clause.
    class SomeClass extends @TypeAnno TypeAnnoDemo<Boolean> {}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿童木-atom

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值