• java lambda怎么表达式判断被调用接口名称和接口中方法


    1.首先能够用于lambda表达式的只能是interface,并且interface 中只有一个方法。

    这就说明,只要找到接口类型就能确定用的是哪个方法。(如下:intTypeInterface、StringTypeInterface、paramInterface)

    2.判断用的哪个接口,通过调用的方法就能确定(如:Test. invoke())

    这里有两种情况

    #1.第一种
    调用的方法名称唯一,没有重载(overload,方法同名,参数个数和类型不同)
    这种情况下直接可以通过方法需要的参数类型即可判断是哪个接口
    如示例中只有一个invoke 方法 void invoke(intTypeInterface a), 即可判断用的是 intTypeInterface。
    
    
    #1.第二种
    调用的方法名称不唯一,有重载(overload,方法同名,参数个数和类型不同)
    这种情况下需要通过invoke方法调用时,lambda表达式中的参数和返回值确定用的是哪个invoke方法。
    
    比如:test.invoke( () -> 1 );
    确定参数为空,返回值为int类型
    在intTypeInterface、StringTypeInterface、paramInterface中, intTypeInterface 中的test 方法满足条件
    确定调用的是invoke(intTypeInterface a)方法
    
    
    

    示例

    
    //下面定义两个functional interface
    interface intTypeInterface { int test(); }
    interface StringTypeInterface { String test(); }
    interface paramInterface { String test(String param); }
    
    class Test {
        //两个同名不同参数不同返回类型的函数
        //函数返回int类型的接口
        void invoke(intTypeInterface a) { System.out.println("intType"); }
        //函数返回String类型的接口
        void invoke(StringTypeInterface b)  { System.out.println("StringType");}
        //函数返回String类型,但是有两个参数的接口
        void invoke(paramInterface b)  { System.out.println("param");}
    
    
        //***如果调用invoke函数会调用哪一个?***//
    
        public static void main(String[] args) {
            Test test = new Test();
    
            //根据 1 返回类型得知应实例化intTypeInterface接口
            test.invoke( () -> 1 );
            //根据 "String" 返回类型得知应实例化StringTypeInterface接口
            test.invoke( () -> "String" );
            //根据函数参数得知应实例化paramInterface接口
            test.invoke( (String s) -> "String" );
    }
    
    
  • 相关阅读:
    集合-ConcurrentSkipListMap 源码解析
    集合-跳表SkipList
    集合-ConcurrentHashMap 源码解析
    >>《移动设计模式大观.pdf》
    >>《《iOS 人机界面准则》中文版.pdf》
    >《Web导航设计.pdf》
    >>《设计心理学名着-2 情感化设计 诺曼着.pdf》
    自制网页(html+css+js+jQuery)
    仿写抽屉新热榜 (html+css)
    运动员喝饮料问题
  • 原文地址:https://www.cnblogs.com/b3051/p/11090553.html
Copyright © 2020-2023  润新知