Class.getCanonicalName() returns null for lambdas

Christoph Dreis christoph.dreis at freenet.de
Fri Jun 5 13:42:16 UTC 2020


Hi,

forgive me if this was discussed already, but I found that the implementation of hidden classes causes a change in behavior for Class.getCanonicalName().

When using the following example code:

interface Function {
	void doSomething();
}

public class Example {

	public static void main(String[] args) {
		Class<? extends Function> lambdaClass = ((Function) () -> {}).getClass();
		String canonicalName = lambdaClass.getCanonicalName();
		System.out.println(canonicalName);
		String name = lambdaClass.getName();
		System.out.println(name);
	}

}

I get the following results:

JDK 14
com.example.demo.Example$$Lambda$14/0x0000000800b66840
com.example.demo.Example$$Lambda$14/0x0000000800b66840

JDK 15
null
com.example.demo.Example$$Lambda$14/0x0000000800b89448

As far as I can tell from the code Lambdas are considered hidden classes now. Is that correct?

I guess Class.getName() should be used instead?

Cheers,
Christoph




More information about the core-libs-dev mailing list