Java8.0 新特性(方法引用)

本文通过四个示例介绍了Java 8中的方法引用概念及其使用方式,包括静态方法引用、对象方法引用、特定类型的方法引用及构造方法引用。

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

方法引用在Java8.0中一共定义了四种形式:

·引用静态方法:类名称::static 方法名称;

·引用某个对象的方法:实例化对象::普通方法;

·引用特定类型的方法:特定类::普通方法;

·引用构造方法:类名称::new


范例1:引用静态方法

interface Message<P, R> {
	public R transFrom(P p);
}

public class Demo {
	public static void main(String[] args) {
		Message<String, Integer> msg = Integer::parseInt;
		int temp = msg.transFrom("200") * 40;
		System.out.println(temp);
	}

}

=============分割线=============

范例2:普通方法引用

interface Message<R> {
	public R upper();
}

public class Demo {
	public static void main(String[] args) {
		Message<String> msg = "hello".substring(0, 4)::toUpperCase;
		String str = msg.upper();
		System.out.println(str);
	}

}

=============分割线=============

范例3:特定类方法引用

interface Message<P> {
	public int compare(P p1, P p2);
}

public class Demo {
	public static void main(String[] args) {
		Message<String> msg = String::compareTo;
		System.out.println(msg.compare("A", "B"));
	}
}

=============分割线=============

范例4:构造方法

interface Message<C> {
	public C create(String str, double num);
}

class Book {
	private String title;
	private double price;

	public Book(String title, double price) {
		this.title = title;
		this.price = price;
	}

	@Override
	public String toString() {
		return "书名:《" + this.title + "》,价格:" + this.price + "元。";
	}
}

public class Demo {
	public static void main(String[] args) {
		Message<Book> msg = Book::new;
		Book bookA = msg.create("Java从入门到精通", 88.8);
		Book bookB = msg.create("Oracle从入门到精通", 99.9);
		System.out.println(bookA);
		System.out.println(bookB);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值