Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a `Class` object, get a method reference to `toString`

If you have only a Class object, how does one get a method reference to a method such as toString? Later we will have instances of this particular class on which we will invoke this method via the method reference.

For example, consider a Java enum, a subclass of Enum. Here T is defined as <T extends Enum>.

Class c = MyEnum.class
…
Function< T , String> f = c :: toString ;

I get an error saying "invalid method reference".

like image 395
Basil Bourque Avatar asked Aug 02 '26 01:08

Basil Bourque


1 Answers

For toString, it's as easy as Object::toString. All Objects have toString, so you can use it right there. For other methods where you don't know statically that the object has that method, there's no easy way; you have to write a lambda that does it the ugly reflective way.

like image 55
Louis Wasserman Avatar answered Aug 04 '26 16:08

Louis Wasserman