简体   繁体   English

框原始类型的方法

[英]Method to box primitive type

Here is a table of primitive types and their equivalent wrapper class. 这是原始类型及其等效包装类的表。

Primitive type  Wrapper class
==============  =============
 boolean        Boolean
 byte           Byte
 char           Character
 float          Float
 int            Integer
 long           Long
 short          Short
 double         Double

I would like to create a method that would convert any given primitive variable into an appropriate class. 我想创建一种将任何给定的原始变量转换为适当类的方法。 I have tried something like below, but that obviously does not work. 我已经尝试过类似下面的操作,但是显然不起作用。 Any help would be appreciated: 任何帮助,将不胜感激:

public static <T> T forceBox(T t) {
  switch (T) {
    case boolean.class : return new Boolean(t);
    case int.class     : return new Integer(t);
    // etc
  }
}

the caller code looks like: 呼叫者代码如下:

int x = 3;
System.out.println("x wrapper type: " + forceBox(x).getClass());

Though this is completely unnecessary in most cases, just use 尽管在大多数情况下这完全没有必要,但只需使用

public static <T> T forceBox(T t) { // compiler will add the conversion at the call site
    return t; 
}

Though you can also just use 虽然你也可以使用

Object o = <some primitive>;

作为装箱过程的一部分,转换已在需要时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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