java由于没有委托,所以创造了函数式接口,用来传递函数,达到函数指针的效果。
例子:
1,lambda表达式实现函数指针
package com.zg.myssm.entities;
/**
* @Auther: Zg
* @Date: 2022/10/24 - 10 - 24 - 20:16
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
public class Demon {
public void runFunc(TestFuncPoint funcPoint){
System.out.println(funcPoint.run("TTTTTTTTTTTTTT"));
}
}
package com.zg.myssm.entities;
/**
* @Auther: Zg
* @Date: 2022/10/24 - 10 - 24 - 20:14
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
// Java中 接口只有一个函数,可以用接口指定函数类型,实现函数指针,委托
public interface TestFuncPoint {
String run(String str);
}
@Test
void Test5(){
Demon demon = new Demon();
System.out.println("===================");
demon.runFunc(MyssmApplicationTests::funcImpl); //类名::方法名,调用函数
System.out.println("===================");
demon.runFunc(t);
}
TestFuncPoint t = (String s)->{return "tttt"+s;};
public static String funcImpl(String str) {
return "hi " + str;
}
//结果:
// ===================
// hi TTTTTTTTTTTTTT
// ===================
// ttttTTTTTTTTTTTTTT
2, 反射实现函数指针
package com.zg.myssm.entities;
import com.fasterxml.jackson.databind.util.ClassUtil;
import javax.lang.model.element.VariableElement;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: Zg
* @Date: 2022/10/24 - 10 - 24 - 21:07
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
public class DemonReflaction {
Map funcMap = new HashMap<String,String >();
public DemonReflaction() {
myinit();
}
private void myinit() {
funcMap.put("猩猩","callLebrown");
funcMap.put("Goat", "callGinnis");
funcMap.put("Hunter","callCurry");
}
public void call(String funcName) throws ClassNotFoundException {
Object methodName = funcMap.get(funcName);
if (methodName != null){
try {
Method method = DemonReflaction.class.getMethod((String) methodName);
Class<?> clazz = Class.forName("com.zg.myssm.entities.DemonReflaction");
//method.invoke(this,null); //对象名,参数
method.invoke(clazz.newInstance(),null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException | InstantiationException e) {
e.printStackTrace();
}
}
}
public void callLebrown() {
System.out.println("I am Lebrown!");
}
public void callGinnis() {
System.out.println("I am Giannis!");
}
public void callCurry() {
System.out.println("I am Hunter!");
}
}
测试:
@Test
void Test6() throws ClassNotFoundException {
DemonReflaction demonReflaction = new DemonReflaction();
demonReflaction.call("猩猩");
}
//结果:I am Lebrown!
3,函数式接口实现 函数指针,委托
package com.zg.myssm.entities;
/**
* @Auther: Zg
* @Date: 2022/10/24 - 10 - 24 - 23:28
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
@FunctionalInterface
public interface TestFuncPointVoid {
void run();
}
package com.zg.myssm.entities;
import java.util.HashMap;
import java.util.Map;
/**
* @Auther: Zg
* @Date: 2022/10/24 - 10 - 24 - 23:33
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
public class DemonVoid {
Map<String, TestFuncPointVoid> funcMap = new HashMap<>();
public DemonVoid(){
myInit();
}
private void myInit() {
funcMap.put("猩猩", this::callCurry);
funcMap.put("Goat", this::callGinnis);
funcMap.put("Hunter",this::callLebrown);
}
public void callLebrown(){
System.out.println("我是Lebrown!!!");
}
public void callGinnis(){
System.out.println("我是Lebrown!!!");
}
public void callCurry(){
System.out.println("我是Lebrown!!!");
}
public void call(String funcName){
TestFuncPointVoid method = funcMap.get(funcName);
if (method != null){
method.run();
}
}
}
@Test
void Test7(){
DemonVoid demonVoid = new DemonVoid();
demonVoid.call("Goat");
}
/*
结果: I am Lebrown!
*/
4,实现事件:
package com.zg.myssm.entities;
/**
* @Auther: Zg
* @Date: 2022/10/25 - 10 - 25 - 0:14
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
@FunctionalInterface
public interface EventPoint {
void run();
}
package com.zg.myssm.entities;
/**
* @Auther: Zg
* @Date: 2022/10/25 - 10 - 25 - 0:15
* @Description: com.zg.myssm.entities
* @version: 1.0
*/
public class EventDemon {
private EventPoint event;
public void submitEvent(EventPoint event){
this.event = event;
}
public void raiseEvent(){
this.event.run();
}
}
@Test
void Test8(){
EventDemon eventDemon = new EventDemon();
//订阅事件:
eventDemon.submitEvent(eventPoint);
//模拟事件发生:
System.out.println("==================");
eventDemon.raiseEvent();
System.out.println("++++++++++++++");
eventDemon.submitEvent(this::buttonPressed);
//模拟事件发生:
eventDemon.raiseEvent();
}
EventPoint eventPoint = ()->{
System.out.println("按下了按钮");
};
public void buttonPressed(){
System.out.println("按下了按钮2");
}
/*
结果:
==================
按下了按钮
++++++++++++++
按下了按钮2
*/
package com.zg.myssm;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zg.myssm.entities.*;
import com.zg.myssm.mapper.DeptMapper;
import com.zg.myssm.mapper.EmpMapper;
import com.zg.myssm.test.Authors;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import sun.plugin.javascript.navig.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@SpringBootTest
class MyssmApplicationTests {
@Autowired
EmpMapper empMapper;
@Autowired
DeptMapper deptMapper;
@Test
void contextLoads() {
QueryWrapper wrapper = new QueryWrapper();
wrapper.like("emp_name","四");
List<Emp> emps = empMapper.selectList(wrapper);
for (Emp emp: emps
) {
System.out.println(emp.toString());
}
}
@Test
void Test2(){
// Emp emp = empMapper.getEmpByEmpId(1);
// System.out.println(emp.toString());
Emp emp = empMapper.getEmpAndDeptByEmpId(1);
System.out.println(emp.toString());
}
//
@Test
void Test3(){
Emp emp = empMapper.getEmpAndDeptByEmpIdEf(1);
System.out.println(emp.toString());
}
//collection
@Test
void Test4(){
Dept dept = deptMapper.myDeptCollectionTest(2);
System.out.println(dept.getEmps().toString());
}
//lambda表达式实现函数指针
//结果:
// ===================
// hi TTTTTTTTTTTTTT
// ===================
// ttttTTTTTTTTTTTTTT
@Test
void Test5(){
Demon demon = new Demon();
System.out.println("===================");
demon.runFunc(MyssmApplicationTests::funcImpl); //类名::方法名,调用函数
System.out.println("===================");
demon.runFunc(t);
}
TestFuncPoint t = (String s)->{return "tttt"+s;};
public static String funcImpl(String str) {
return "hi " + str;
}
//反射实现函数指针
//结果:I am Lebrown!
@Test
void Test6() throws ClassNotFoundException {
DemonReflaction demonReflaction = new DemonReflaction();
demonReflaction.call("猩猩");
}
// 函数式接口实现 函数指针,委托
@Test
void Test7(){
DemonVoid demonVoid = new DemonVoid();
demonVoid.call("Goat");
}
//实现事件
@Test
void Test8(){
EventDemon eventDemon = new EventDemon();
//订阅事件:
eventDemon.submitEvent(eventPoint);
//模拟事件发生:
System.out.println("==================");
eventDemon.raiseEvent();
System.out.println("++++++++++++++");
eventDemon.submitEvent(this::buttonPressed);
//模拟事件发生:
eventDemon.raiseEvent();
}
EventPoint eventPoint = ()->{
System.out.println("按下了按钮");
};
public void buttonPressed(){
System.out.println("按下了按钮2");
}
/*
结果:
==================
按下了按钮
++++++++++++++
按下了按钮2
*/
@Test
public void Test9(){
Demon demon = new Demon();
demon.runFunc(new TestFuncPoint() {
@Override
public String run(String str) {
return null;
}
});
demon.runFunc((String str)->{
return str;
});
}
@Test
public void Test10() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
Class clazz = Class.forName("com.zg.myssm.entities.Demon");
//获取方法 方法名,参数类型
Method runFunc = clazz.getMethod("runFunc", TestFuncPoint.class);//方法名,参数类型
runFunc.setAccessible(true);
TestFuncPoint p = (String str) -> {
return str;
};
//对象,参数数据
runFunc.invoke(clazz.newInstance(), p);
System.out.println(runFunc);
}
@Test
public void Test11(){
// printNum_(new IntPredicate() {
// @Override
// public boolean test(int value) {
// return value%2==0;
// }
// });
// 结果:2,4,6,8
printNum_((int value)->{
return value%2==0;
});
}
public void printNum(IntPredicate predicate){
int[] arr = {1,2,3,4,5,6,7,8,9};
Arrays.asList(arr).forEach(a->{
System.out.println(a);
});
}
public void printNum_(IntPredicate predicate){
Integer[] arr = {1,2,3,4,5,6,7,8,9};
//List<Integer> ints = Arrays.asList(arr);
//调用了test方法,返回bool
List<Integer> integers = Arrays.asList(arr);
// integers.stream().filter(new Predicate<Integer>() {
// @Override
// public boolean test(Integer integer) {
// return false;
// }
// })
Arrays.asList(arr).forEach(new Consumer<Integer>() {
@Override
public void accept(Integer integer) {
}
});
Arrays.asList(arr).forEach(a->{
if (predicate.test(a))
System.out.println(a);
});
}
@Test
public void Test12(){
Authors authors1 = new Authors();
List<Author> authors = authors1.getAuthors();
authors.stream().distinct().filter((author)-> author.getAge()<18
).forEach(author -> author.getName());
}
//map
@Test
public void Test15(){
Authors authors1 = new Authors();
List<Author> authors = authors1.getAuthors();
authors.stream().map(author -> author.getName()).forEach(System.out::println);
/*
写下 new Function 修改完String 后 按enter
authors.stream().map(new Function<Author, String>() {
@Override
public String apply(Author author) {
return author.getName();
}
});
*/
}
//终结操作,返回List
@Test
public void Test16(){
Authors authors1 = new Authors();
List<Author> authors = authors1.getAuthors();
List<String> collect = authors.stream().filter(a->a.getAge()<18).map(Author::getName).distinct().collect(Collectors.toList());
collect.forEach(name-> System.out.println(name));
/*
结果:亚拉索 易
*/
System.out.println("====================");
//返回两个字段:
Map<String, Integer> collect1 = authors.stream().filter(a -> a.getAge() < 18).distinct().collect(Collectors.toMap(a->a.getName(), Author::getAge));
for (Map.Entry<String,Integer> map:collect1.entrySet()
) {
System.out.println(map.getKey());
System.out.println(map.getValue());
}
/*
结果:亚拉索
15
易
14
*/
}
@Test //sort
public void Test17(){
Authors myauthors = new Authors();
List<Author> authors = myauthors.getAuthors();
authors.stream().sorted(Comparator.comparingInt(Author::getAge)).forEach(x-> System.out.println(x.toString()));
}
//双冒号:
//system.out::println 适用于 x->system.out.println(x)输出本身。可以用map 映射 成要打印的字段。
//collect是终结操作,输出List为Collectors.toList()
@Test
public void Test18(){
Authors myAuthors = new Authors();
List<Author> authors = myAuthors.getAuthors();
authors.stream().filter(x -> x.getAge() < 18).distinct().map(Author::getName).forEach(System.out::println);
}
}
@Test
public void Test19(){
LambdaQueryWrapper<Emp> wrapper = new LambdaQueryWrapper<>();
List<Emp> emps = empMapper.selectList(wrapper.ge(Emp::getAge,18).like(Emp::getEmpName,"张"));
emps.forEach(System.out::println);
LambdaUpdateWrapper<Emp> updateWrapper = new LambdaUpdateWrapper<>();
//名字带张 且(年龄大于18,性别不为空)
updateWrapper.like(Emp::getEmpName,"张").and(e -> e.gt(Emp::getAge,18).or().isNull(Emp::getGender));
//修改
updateWrapper.set(Emp::getEmpName,"张四").set(Emp::getAge,999);
int update = empMapper.update(null, updateWrapper);
}
博客介绍了Java因无委托而创造函数式接口来传递函数以达函数指针效果,还列举了通过lambda表达式、反射实现函数指针的例子,以及函数式接口实现函数指针和委托、实现事件的测试内容。
222

被折叠的 条评论
为什么被折叠?



