如何在 Java 中使用方法引用实现任意对象的实例方法?
方法引用是 Java 8 中的一项新特性,它与Lambda 表达式相关。它允许我们在不执行它们的情况下引用构造函数和方法。方法引用和Lambda 表达式类似,因为它们都需要一个目标类型,该类型由兼容的功能界面组成。
语法
Class :: instanceMethodName
示例
import java.util.*; import java.util.function.*; public class ArbitraryObjectMethodRefTest { public static void main(String[] args) { List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Raja", 30)); persons.add(new Person("Jai", 25)); persons.add(new Person("Adithya", 20)); persons.add(new Person("Surya", 35)); persons.add(new Person("Ravi", 32)); List ages = ArbitraryObjectMethodRefTest.listAllAges(persons, Person :: getAge); System.out.println("Printing out all ages:
" + ages); } private static List listAllAges(List person, Function<Person, Integer> f) { List result = new ArrayList(); person.forEach(x -> result.add(f.apply((Person)x))); return result; } private static class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } }
输出
Printing out all ages: [30, 25, 20, 35, 32]
广告