Java SE8结构与新增功能

2019-06-25  本文已影响0人  风吹柳_柳随风

Java8简介

        摘自官文文档
        Oracle的Java SE8包含了两个产品:Java SE开发套件(JDK)8和Java SE运行环境(JRE)8。
        JDK8是JRE8的超集,它包含了JRE8中所含有的一切,以及开发applet和应用程序所需的编译器和调试器等工具。JRE8提供了运行用java程序语言编写的applets和程序所需要的类库,java虚拟机(jvm)和其他组件。需要注意的是,JRE包含Java SE规范不需要的组件,包括标准和非标准Java组件。
        以下概念图说明了Oracle Java SE产品的组件:
        Java概念图

java概念图

Java7,Java8新增功能

摘自官方文档

Java7新增功能

// An 8-bit 'byte' value:
byte aByte = (byte)0b00100001;

// A 16-bit 'short' value:
short aShort = (short)0b1010000101000101;

// Some 32-bit 'int' values:
int anInt1 = 0b10100001010001011010000101000101;
int anInt2 = 0b101;
int anInt3 = 0B101; // The B can be upper or lower case.

// A 64-bit 'long' value. Note the "L" suffix:
long aLong = 0b1010000101000101101000010100010110100001010001011010000101000101L;
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi =      3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;

注意!你不能在如下场景下使用:

  1. 不能在文字的开头或结尾使用下划线!
  2. 不能与浮点数中的小数点相邻!
  3. 不能在L或F后缀之前使用!
  4. 不能在预期是一串数字的位置上使用!
    示例代码:
float pi1 = 3_.1415F;      // Invalid; cannot put underscores adjacent to a decimal point
float pi2 = 3._1415F;      // Invalid; cannot put underscores adjacent to a decimal point
long socialSecurityNumber1
  = 999_99_9999_L;         // Invalid; cannot put underscores prior to an L suffix

int x1 = _52;              // This is an identifier, not a numeric literal
int x2 = 5_2;              // OK (decimal literal)
int x3 = 52_;              // Invalid; cannot put underscores at the end of a literal
int x4 = 5_______2;        // OK (decimal literal)

int x5 = 0_x52;            // Invalid; cannot put underscores in the 0x radix prefix
int x6 = 0x_52;            // Invalid; cannot put underscores at the beginning of a number
int x7 = 0x5_2;            // OK (hexadecimal literal)
int x8 = 0x52_;            // Invalid; cannot put underscores at the end of a number

int x9 = 0_52;             // OK (octal literal)
int x10 = 05_2;            // OK (octal literal)
int x11 = 052_;            // Invalid; cannot put underscores at the end of a number
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
     String typeOfDay;
     switch (dayOfWeekArg) {
         case "Monday":
             typeOfDay = "Start of work week";
             break;
         case "Tuesday":
         case "Wednesday":
         case "Thursday":
             typeOfDay = "Midweek";
             break;
         case "Friday":
             typeOfDay = "End of work week";
             break;
         case "Saturday":
         case "Sunday":
             typeOfDay = "Weekend";
             break;
         default:
             throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
     }
     return typeOfDay;
}
//Java7之前
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
//Java7
Map<String, List<String>> myMap = new HashMap<>();

/*Java SE 7 supports limited type inference for generic instance creation; 
you can only use type inference if the parameterized type of the constructor is 
obvious from the context.*/
List<String> list = new ArrayList<>();
list.add("A");
  // The following statement should fail since addAll expects
  // Collection<? extends String>
list.addAll(new ArrayList<>());
/*Note that the diamond often works in method calls; 
however, it is suggested that you use the diamond primarily for variable declarations.*/
// The following statements compile:
List<? extends String> list2 = new ArrayList<>();
list.addAll(list2);

non-reifiable类型是指在运行期无法完全获得的类型,例如ArrayList<Number>List<String>等等。
原文:Most parameterized types, such as ArrayList<Number> and List<String>, are non-reifiable types. A non-reifiable type is a type that is not completely available at runtime.
示例代码:

public class ArrayBuilder {

  public static <T> void addToList (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  @SuppressWarnings({"unchecked", "varargs"})
  public static <T> void addToList2 (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  @SafeVarargs
  public static <T> void addToList3 (List<T> listArg, T... elements) {
    for (T x : elements) {
      listArg.add(x);
    }
  }

  // ...

}
public class HeapPollutionExample {

  // ...

  public static void main(String[] args) {

    // ...

    ArrayBuilder.addToList(listOfStringLists, stringListA, stringListB);
    ArrayBuilder.addToList2(listOfStringLists, stringListA, stringListB);
    ArrayBuilder.addToList3(listOfStringLists, stringListA, stringListB);

    // ...

  }
}
//定义一个资源
static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    return br.readLine();
  }
}

//定义多个资源
 public static void writeToFileZipFileContents(String zipFileName, String outputFileName)
    throws java.io.IOException {

    java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with try-with-resources statement
    try (
      java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName);
      java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {

      // Enumerate each entry
      for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) {

        // Get the entry name and write it to the output file

        String newLine = System.getProperty("line.separator");
        String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine;
        writer.write(zipEntryName, 0, zipEntryName.length());
      }
    }
  }
//Handling More Than One Type of Exception
catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

// Rethrowing Exceptions with More Inclusive Type Checking
public void rethrowException(String exceptionName)
  throws FirstException, SecondException {
    try {
      // ...
    }
    catch (Exception e) {
      throw e;
    }
  }

Java8新增功能

public class Person {

    public enum Sex {
        MALE, FEMALE
    }

    String name;
    LocalDate birthday;
    Sex gender;
    String emailAddress;

    public int getAge() {
        // ...
    }
    
    public Calendar getBirthday() {
        return birthday;
    }    

    public static int compareByAge(Person a, Person b) {
        return a.birthday.compareTo(b.birthday);
 }}

//Reference to a Static Method
Arrays.sort(rosterAsArray, Person::compareByAge);

//Reference to an Instance Method of a Particular Object
class ComparisonProvider {
    public int compareByName(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
        
    public int compareByAge(Person a, Person b) {
        return a.getBirthday().compareTo(b.getBirthday());
    }
}
ComparisonProvider myComparisonProvider = new ComparisonProvider();
Arrays.sort(rosterAsArray, myComparisonProvider::compareByName);

//Reference to a Constructor
public static <T, SOURCE extends Collection<T>, DEST extends Collection<T>>
    DEST transferElements(
        SOURCE sourceCollection,
        Supplier<DEST> collectionFactory) {
        
        DEST result = collectionFactory.get();
        for (T t : sourceCollection) {
            result.add(t);
        }
        return result;
}

Set<Person> rosterSetLambda = transferElements(roster, () -> { return new HashSet<>(); });
// or
Set<Person> rosterSet = transferElements(roster, HashSet::new);
// or
Set<Person> rosterSet = transferElements(roster, HashSet<Person>::new);
List<String> stringList = new ArrayList<>();
stringList.add("A");

//在java7中这段会编译出错
stringList.addAll(Arrays.asList());

        你可以在以下的Java教程中获取更多相关的信息:
        1. Target Typing in Lambda Expressions
        2. Type Inference

//Class instance creation expression
new @Interned MyObject();

//Type cast
myString = (@NonNull String) str;

//implements clause
class UnmodifiableList<T> implements
        @Readonly List<@Readonly T> { ... }

//Thrown exception declaration
void monitorTemperature() throws
        @Critical TemperatureException { ... }

        这种形式的注释称为类型注释。更多信息请查阅 Type Annotations and Pluggable Type Systems

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

@Alert(role="Manager")
@Alert(role="Administrator")
public class UnauthorizedAccessException extends SecurityException { ... }
public class Annotation {
    
    private static final String  fmt = "%24s: %s%n";
    private String name;
    private String method;
    
    public Annotation(String name, String method){
        this.name = name;
        this.method = method;
    }
    
    public static void main(String[] args) {
        Class<? extends Annotation> clazz = Annotation.class;
        Constructor<?>[] constructors = clazz.getConstructors();
        for(Constructor<?> constructor : constructors){
            for(Parameter p : constructor.getParameters()){
                printParameter(p);
            }
            
        }
    }
    
    public static void printParameter(Parameter p) {
        System.out.format(fmt, "Parameter class", p.getType());
        System.out.format(fmt, "Parameter name", p.getName());
        System.out.format(fmt, "Modifiers", p.getModifiers());
        System.out.format(fmt, "Is implicit?", p.isImplicit());
        System.out.format(fmt, "Is name present?", p.isNamePresent());
        System.out.format(fmt, "Is synthetic?", p.isSynthetic());
    }
}

输出结果:


Method Parameter Reflection
上一篇下一篇

猜你喜欢

热点阅读