简体   繁体   中英

How do I get the reference type corresponding to a primitive type?

我想要一个将类映射到类的函数,例如int.class-> Integer。

Primitives.wrap(Class) JDK中没有专门提供此功能,但是如果您不想自己动手, Guava提供了Primitives.wrap(Class) ,它接受基本类型并返回相应的包装器类型。

For integer:

int.class or the equivalent: Integer.TYPE;

Same for other primitive types

double.class or Double.TYPE
float.class or Float.TYPE
char.class or Character.TYPE
long.class or Long.TYPE
boolean.class Boolean.TYPE

Use it as follows:

Class intClass = int.class;

This then is a class that represents the primitive type int.

With that info, you simply write your own mapper: (You dont want to include an external lib for 8 lines of code)

public Class getClassForPrimitiveType(Class clazz) {
  if (clazz == int.class) return Integer.class;
  if (clazz == float.class) return Float.class;
  // TODO other primitives
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM