Retrolambda
Retrolambda
的功能如官方所描述的那样
Retrolambda lets you run Java 8 code with lambda expressions, method references and try-with-resources statements on Java 7, 6 or 5.
使Java 7,6,5支持Java 8中的lambda
表达式,方法引用,try-with-resources
语句等特性。
JDK 8
安装JDK 8
,并将其设置为默认JDK
Gradle Retrolambda Plugin
在Android Studio中使用Retrolambda最方便的方式是使用gradle-retrolambda插件
build.gradle
修改app模块下的build.gradle文件
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.6.1'
}
}
// Required because retrolambda is on maven central
repositories {
mavenCentral()
}
apply plugin: 'me.tatarka.retrolambda'
...
android {
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}
...
}
使用
package me.zongren.retrolambdademo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView)findViewById(R.id.textView);
//lambda
textView.setOnClickListener(view -> clickTextView(view));
//method reference
textView.setOnClickListener(this::clickTextView);
}
private void clickTextView(View view) {
}
}
官方文档
Oracle官方文档可以看这里:Lambda Expressions,Method References,The try-with-resources Statement