Java7-11新语法特性
Java 7
1. 以前泛型初始化⽐较⿇烦,现在对于Map<String, List<Trade>> trades = new TreeMap<String, List<Trade>> ();这种初始化,可以直接推测Map<String, List<Trade>> trades = new TreeMap <> ();
2. 引⼊switch
public class StringInSwitchStatementExample {
public static void main(String[] args) {
String game = "Card-Games";
switch(game){
case "Hockey": case"Cricket": case"Football":
System.out.println("This is a outdoor game");
break;
case "Chess": case"Card-Games": case"Puzzles": case"Indoor basketball":
System.out.println("This is a indoor game");
break;
default:
System.out.println("What game it is?");
}
}
}
3. ⾃动资源分配 try(someresource),不需要再⽤try{...}finally{close()}
还可以⽤;分割来⼀次申请多个资源,⽐如: try(FileOutputStream fos = newFileOutputStream("");DataOutputStream dos = newDataOutputStream(fos)) {
不过这些资源需要实现AutoCloseable接⼝(是java.io.Closeable的⽗接⼝)。
4. 引⼊数字常量中的下划线,⽐如1_000_000
5. 在⼀个catch中catch多种exception。catch(ExceptionOne | ExceptionTwo | ExceptionThree e)
6. 新的File System API(nio2.0)
⽐如:
Path path= ("c:\Temp\temp");
Files.delete(path);
Files.deleteIfExists(path)
能⽤WatchService来获取dir或者file变更的通知
WatchService  watchService = Default().newWatchService();
while(true)
{
WatchKey key = watchService.take();
for(WatchEvent<?> event : key.pollEvents()) {
Kind<?> kind = event.kind();
/
/do sth
}
  set();
}
7. ForkJoinTask & ForkJoinPool
ForkJoinTask可以是RecursiveAction或者RecursiveTask,这⾥前者不返回
ForkJoinPool Pool = new ForkJoinPool(proc);
TaskA tk=new TaskA(arg1);
T t = Pool.invoke(tk);
Pool.awaitTermination(3, TimeUnit.SECONDS);
Pool.awaitQuiescence(2, TimeUnit.SECONDS);
Pool.isTerminating();
TaskA tk2=new TaskA(arg1);
Pool.submit(tk3);
Pool.shutdown();
class TaskA extends RecursiveTask<T> {
TaskA(T argT) { }
protected T compute() {
return new T();
}
}
ForkJoinPool fpool = new ForkJoinPool();
TaskA tk = new TaskA();
ForkJoinTask<String> Sfpool = ForkJoinTask.adapt(tk,"OK");
fpool.invoke(Sfpool);
if(Sfpool.isDone())
System.out.println(Sfpool.join()); //OK,功效相当于在tk结束之后返回⼀个OK
这⾥ForkJoinTask.adapt提供⼀个运⾏Runnable并且返回可选的预定result的新ForkJoinTask。
8. invokeDynamic,此外,Java 7引⼊了新的java.lang.invoke包,⾥⾯有MethodHandle和CallSite等功能。
public class Main {
public static void main(String[] args) {
long lengthyColors = List.of("Red", "Green", "Blue")
.stream().filter(c -> c.length() > 3).count();
}
}
javap -c -p Main
// truncated
// class names are simplified for the sake of brevity
// for instance, Stream is actually java/util/stream/Stream
0: ldc              #7            // String Red
2: ldc              #9            // String Green
4: ldc              #11            // String Blue
6: invokestatic      #13            // InterfaceMethod List.of:(LObject;LObject;)LList;
9: invokeinterface  #19,  1        // InterfaceMethod List.stream:()LStream;
14: invokedynamic    #23,  0        // InvokeDynamic #0:test:()LPredicate;
19: invokeinterface  #27,  2        // InterfaceMethod Stream.filter:(LPredicate;)LStream;
24: invokeinterface  #33,  1        // unt:()J
29: lstore_1
30: return
这⾥filter新建了⼀个Predicate实例,并且调⽤了invokedynamic。调⽤对象是⼀个匿名成员函数,在BootstrapMethod Table的第0个。
private static boolean lambda$main$0(java.lang.String);
Code:
0: aload_0
1: invokevirtual #37                // Method java/lang/String.length:()I
4: iconst_3
5: if_icmple    12
8: iconst_1
9: goto          13
12: iconst_0
13: ireturn
引⽤来⾃www.baeldung/java-invoke-dynamic
当JVM第⼀次看到invokeDynamic的时候会调⽤⼀个特殊的⽅法Bootstrap来进⾏初始化。Bootstrap是⽤来invocation process的,可以包含任何逻辑。当bootstrap调⽤完成之后,会返回⼀个CallSite实例,这个CallSite实例中封装了以下信息:
1. 指向JVM应当执⾏的实际逻辑的指针MethodHandle
2. 条件变量,⽤来指⽰CallSite是否可⽤。
之后JVM就不会再次调⽤bootstrap⽽是会直接⽤CallSite中的MethodHandle了。
与Reflection不同,JVM会试着优化MethodHandle中的代码。
此时列出BootstrapTable。可以看到,所有bootstrap method都存在afactory⾥⾯。
javap -c -p -v Main
// truncated
// added new lines for brevity
BootstrapMethods:
0: #55 REF_invokeStatic java/lang/afactory:
(Ljava/lang/invoke/MethodHandles$Lookup;
Ljava/lang/String;
Ljava/lang/invoke/MethodType;
Ljava/lang/invoke/MethodType;
Ljava/lang/invoke/MethodHandle;
Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;
Method arguments:
#62 (Ljava/lang/Object;)Z
#64 REF_invokeStatic Main.lambda$main$0:(Ljava/lang/String;)Z
#67 (Ljava/lang/String;)Z
注意bootstrap返回的是ConstantCallSite。此外,java还提供了MutableCallSite和VolatileCallSite功能,也能实现类似逻辑。
9. JDBC: 提供了RowSetFactory, RowSetProvider, RowSet,CachedRowSet, JdbcRowSet等。
import wset.JdbcRowSet;
import wset.RowSetProvider;
class JdbcExample{
public staticvoid main(String args[]) throws Exception{
try(// --------------try-with-resources begin-------------//
// Creating connection
JdbcRowSet jRS = wFactory().createJdbcRowSet();
)// --------------try-with-resources end--------------//
{ // ----------------try block begin---------------------//
// Set database connection
jRS.setUrl("jdbc:mysql://localhost:3306/student");
// Set database username
jRS.setUsername("root");
// Set database password
jRS.setPassword("mysql");
// Set sql query to execute
jRS.setCommand("select * from user");
// Execute query
/
/ Getting 3rd row because it is scrollable by default
jRS.absolute(3);
System.out.Int(1)+""+String(2)+""+String(3));
// Updating 3rd row
jRS.updateString("name", "Neraj Kumar Singh");
jRS.updateRow();
// Fetching 3rd row again
System.out.Int(1)+""+String(2)+""+String(3));
// Set sql query to execute
jRS.setCommand("select * from user");
// Execute query
()){
System.out.Int(1)+""+String(2)+""+String(3));
}
} // ----------------try block end----------------------//
catch(Exception e){ // Exception handler
System.out.println(e);
}
}
}
Java 8
1. lambda expression,基本结构(args)->{dosth;return sth2;}
例⼦来⾃javatpoint
Sayable s2= name ->{
return "Hello, "+name;
};
Addable ad2=(int a,int b)->(a+b);
list.forEach(
(n)->System.out.println(n)
);
Runnable r2=()->{
System.out.println("Thread2 ");
};
Thread t2=new Thread(r2);
t2.start();
Collections.sort(list,(p1,p2)->{
return p1.namepareTo(p2.name);
});
Stream<Product> filtered_data = list.stream().filter(p -> p.price > 20000);
b.addActionListener(e-> {tf.setText("hello swing");});
2. Method Reference
a) Reference to a Static Method:基本语法Class::staticMethod
例如,可以定义⼀个functional interface,然后把⼀个参数构成相同的静态⽅法引⽤为该interface实例。interface Sayable{
void say();
}
public class MethodReference {
public static void saySomething(){
System.out.println("Hello, this is static method.");
}
public static void main(String[] args) {
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();  //Hello, this is static method.
}
}
以下实例则直接将静态⽅法转化为Runnable接⼝:
public class MethodReference2 {
public static void ThreadStatus(){
System.out.println("Thread ");
}
public static void main(String[] args) {
Thread t2=new Thread(MethodReference2::ThreadStatus);
t2.start();
}
}
还能⽤静态⽅法来override另⼀个类中的静态⽅法。
import java.util.function.BiFunction;
class Arithmetic{
public static int add(int a, int b){
return a+b;
}
public static float add(int a, float b){
return a+b;
}
public static float add(float a, float b){
return a+b;
}
}
public class MethodReference4 {
public static void main(String[] args) {
BiFunction<Integer, Integer, Integer>adder1 = Arithmetic::add;
BiFunction<Integer, Float, Float>adder2 = Arithmetic::add;java switch case string
BiFunction<Float, Float, Float>adder3 = Arithmetic::add;
int result1 = adder1.apply(10, 20);
float result2 = adder2.apply(10, 20.0f);
float result3 = adder3.apply(10.0f, 20.0f);
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
}
}
b) Ref to an instance method: obj::methodname
public class InstanceMethodReference2 {
public void printnMsg(){
System.out.println("Hello, this is instance method");
}
public static void main(String[] args) {
Thread t2=new Thread(new InstanceMethodReference2()::printnMsg);
t2.start();
}
}
c) Ref to a Constructor: class::new
interface Messageable{
Message getMessage(String msg);
}
class Message{
Message(String msg){
System.out.print(msg);
}
}
public class ConstructorReference {
public static void main(String[] args) {
Messageable hello = Message::new;
}
}
3. 下划线变成了keyword,不能再直接⽤来当变量名了。
4. 提供了defaultStream和staticStream两个类。提供了takeWhile, dropWhile。
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
List<Integer> list
= Stream.of(2,2,3,4,5,6,7,8,9,10)
.takeWhile(i -> (i % 2 == 0)).List());
System.out.println(list);  //[2,2]
}
}
dropwhile类似。
创建时也有两个值得⼀提的⽅法-ofNullable和iterate。
ofNullable,也就是Stream.of,当传⼊的是null的时候,返回empty stream,更⽅便处理null stream和NullPointerException。Stream<Integer> val = Stream.ofNullable(null);
iterate(seed; hasNext;next)
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
Stream.iterate(1, i -> i <= 10, i -> i*3)
.forEach(System.out::println);
}
}
5. 引⼊Module,⽤来管理多个package。能够⽣成Modular JAR。这个JAR会包含⼀个⽤来描述信息的module-info.class。此外,还能⽣成JMOD格式,这个格式与JAR相似,但是能够包含源代码和config⽂件。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。