I have a piece of code where I need to pass the class of a field in a method. Because of the mechanics of my code I can only handle reference objects and not primitives. I w
With a more recent jdk, this is a one-liner now:
@SuppressWarnings("unchecked")
public static Class wrap(Class c) {
return (Class) MethodType.methodType(c).wrap().returnType();
}
@SuppressWarnings("unchecked")
public static Class unwrap(Class c) {
return (Class) MethodType.methodType(c).unwrap().returnType();
}
Here is a test that I wrote using JMH and here are the results:
Benchmark Mode Cnt Score Error Units
PrimitiveToWrapper.ifStatements avgt 30 42.112 ± 0.716 ns/op
PrimitiveToWrapper.map avgt 30 45.018 ± 0.923 ns/op
PrimitiveToWrapper.wrap avgt 30 52.369 ± 0.836 ns/op
The difference is rather small.