java基础九(方法引用)

博客介绍了引用操作最初针对类、接口、数组等引用类型,现在追加了方法引用,其形式有引用静态方法、引用某个对象的方法、引用某个特定类的方法、引用构造方法四类,并给出了String中valueOf()方法等范例,还指出代码存在不好读且混乱的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 从最初的开始基本上进行的引用基本上都是针对引用类型完成的,也就是说只有类、接口、数组具备引用的操作。现在追加了方法的引用。实际上就是为了别名。
    方法的引用形式有四类:
    a).引用静态方法:类名称 :: static方法名称(静态方法名称)
    b).引用某个对象的方法:实例化对象 :: 普通方法
    c).引用某个特定类的方法:类名称 :: 普通方法
    d).引用构造方法: 类名称 ::new
    范例:
    String 中的valueOf() 这个方法就是静态调用的。
    1.引用静态方法范例:
interface IMessage1<P,R> {
   public R zhuanhuan(P p);
}
public class test {

    public static void main(String [] args) {
        IMessage1<Integer,String> im = String ::valueOf;
        String test = im.zhuanhuan(100);
        System.out.println(test.length());
    }
}

2.引用对象的某个方法

interface IMessage1<R> {
   public R zhuanhuan();
}
public class test {

    public static void main(String [] args) {
        IMessage1<String> im = "hello" :: toUpperCase;
        String test = im.zhuanhuan();
        System.out.println(test);
    }
}

3.引用特定类的方法

@FunctionalInterface
interface IMessage1<R,P> {
   public R compare(P a, P b);
}
public class test {

    public static void main(String [] args) {
        IMessage1<Integer,String> im = String :: compareTo;
        Integer test = im.compare("H","h");
        System.out.println(test);
    }
}

4.引用构造方法

@FunctionalInterface
interface IMessage1<R,FP,SP> {
   public R compare(FP a, SP b);
}
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }
}
public class test {

    public static void main(String [] args) {
        IMessage1<Person, String, Integer> im = Person :: new;
        System.out.println(im.compare("zhangsan",20));
    }
}

这种代码不好读 还混乱。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值