目錄Java8 介面初始化的幾種場景通過介面實現類的方式實現代碼實現通過匿名內部類的來實現代碼實現通過JDK8 雙冒號用法方式代碼實現通過箭頭函數Lambda表達式的方式代碼實現將介面作為方法參數代碼實現 Java8 介面初始化的幾種場景 通過介面實現類的方式實現 代碼實現 public inter ...
目錄
Java8 介面初始化的幾種場景
通過介面實現類的方式實現
代碼實現
public interface MyService {
void sayMessage(String message);
default void doWork1() { System.out.println("doWork"); }
static void printHello() {System.out.println("Hello"); }
}
//介面實現
public class MyServiceImpl implements MyService{
@Override
public void sayMessage(String message) {
System.out.println(message);
}
}
//測試方法
MyService myService=new MyServiceImpl();
myService.sayMessage("hello,welcome");
//hello,welcome
通過匿名內部類的來實現
代碼實現
MyService myService=new MyService(){
@Override
public void sayMessage(String message) {
System.out.println(message);
}
};
//測試方法
myService.sayMessage("hello,welcome");
//hello,welcome
通過JDK8 雙冒號用法方式
代碼實現
void showMessage(String mssage){
System.out.println(mssage);
}
MyService myService3=this::showMessage;
myService3.sayMessage("hello,jack");
通過箭頭函數Lambda表達式的方式
代碼實現
//定義函數式介面
@FunctionalInterface
public interface YourService<T,R> {
List<R> map(List<T> src, Function<T, R> mapper, Class<R> targetType);
}
/*@FunctionalInterface 註解申明一個函數式介面,這樣就可以採用箭頭函數的方式來實現介面,如果介面中預設只定義了一個方法,則@FunctionalInterface註解可以省略
*/
// 介面實現
//通過箭頭函數Lambda表達式來實現
YourService<Student, Person> ysImpl = (item1, item2, item3) -> {
List<Person> persons2 = new ArrayList<Person>();
for (Student stu : item1) {
persons2.add(item2.apply(stu));
}
return persons2;
};
//測試
List<Student> students = new ArrayList<Student>() {
{
add(new Student(0, 10, "a"));
add(new Student(1, 20, "b"));
add(new Student(2, 30, "c"));
add(new Student(3, 40, "d"));
}
};
List<Person> personsBew = ysImpl.map(students, (r) -> {
Person person = new Person();
BeanUtils.copyProperties(r, person);
return person;
}, Person.class);
System.out.println(personsBew.toString());
[TestRunner.Person(id=0, age=10, firstName=a), TestRunner.Person(id=1, age=20, firstName=b), TestRunner.Person(id=2, age=30, firstName=c), TestRunner.Person(id=3, age=40, firstName=d)]
將介面作為方法參數
代碼實現
//將介面作為方法形參
private <T, R> void testMethod(List<T> rList, YourService<T, R> service, Class<R> target) {
List<R> rlist = service.map(rList, (t) -> {
R r = null;
try {
r = (R) target.newInstance();
BeanUtils.copyProperties(t, r);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
System.out.println(e.toString());
}
return r;
}, target);
System.out.println(rlist.toString());
}
//調用方法並實現介面方法
testMethod(students, (item1, item2, item3) -> {
List<Person> persons2 = new ArrayList<Person>();
for (Student stu : item1) {
persons2.add(item2.apply(stu));
}
return persons2;
}, Person.class);