🐥

【Java】メソッド参照

に公開

メソッド参照とは

  • すでに定義済みのメソッドを呼び出して実行出来る書き方
  • 引数が省略出来るので、ラムダ式より記述量が減らすことが可能
  • Java8より導入された

構文

対象 書き方
クラスメソッド クラス名::メソッド名
インスタンスメソッド インスタンス名::メソッド名
コンストラクタ クラス名::new コンストラクタ

使用例

クラスメソッド

package methodReferenceTest;

import java.util.function.Function;

public class Main {
	public static void main(String[] args) {
		// ラムダ式を使う場合
		Function<String, Integer> toIntLambda = s -> Integer.parseInt(s);

		// メソッド参照を使う場合(より短い)
		Function<String, Integer> toIntMethodRef = Integer::parseInt;

		System.out.println(toIntLambda.apply("123")); // 123
		System.out.println(toIntMethodRef.apply("456")); // 456
	}
}

インスタンスメソッド

package methodReferenceTest;

import java.util.function.Function;

public class MainToUpperCase {
	public static void main(String[] args) {
		Function<String, String> toUpperLambda = s -> s.toUpperCase(); // ラムダ式
		Function<String, String> toUpperMethodRef = String::toUpperCase; // メソッド参照

		System.out.println(toUpperLambda.apply("hello")); // HELLO
		System.out.println(toUpperMethodRef.apply("world")); // WORLD
	}
}

コンストラクタ

newを使用してインスタンス生成を行う

引数なし

package methodReferenceTest.noArguments;

public class Person {
	public Person() {
		System.out.println("Personインスタンスが作成されました!");
	}
}
package methodReferenceTest.noArguments;

import java.util.function.Supplier;

public class MainPersonNoArguments {
	public static void main(String[] args) {
		Supplier<Person> personSupplier = Person::new;
		//Personインスタンスが作成されました!
		personSupplier.get();
	}
}

引数あり

package methodReferenceTest.arguments;

public class Person {
	private String name;

	public Person(String name) {
		this.name = name;
		System.out.println("Person が作成されました: " + name);
	}
}
package methodReferenceTest.arguments;

import java.util.function.Function;

public class MainPersonArguments {
	public static void main(String[] args) {
		//Stringを受取り、Personインスタンスを返す
		Function<String, Person> personCreator = Person::new;
		//Person が作成されました: 太郎
		Person person = personCreator.apply("太郎");
		//Person が作成されました: 花子
		Person person2 = personCreator.apply("花子");
	}
}

その他の例

package methodReferenceTest;

import java.util.Arrays;
import java.util.List;

public class MainListTest {
	public static void main(String[] args) {
		List<String> names = Arrays.asList("高橋田", "大川山", "杉原野");
		names.forEach(System.out::println);
	}
}

<出力例>

https://zenn.dev/codek2/articles/7fbfa22ba62e69

Udemyで講座を公開中!
https://zenn.dev/codek2/articles/e9e44f3e0023fb

X(旧Twitter)
https://twitter.com/kunchan2_

Zenn 本
https://zenn.dev/codek2?tab=books

Youtube
https://www.youtube.com/@codek2_studio

Discussion