Simple way to get wrapper class type in Java

前端 未结 9 1441
天命终不由人
天命终不由人 2020-11-29 09:14

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

9条回答
  •  眼角桃花
    2020-11-29 09:47

    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.

提交回复
热议问题