java中接口的实现方式
目录
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);