有人告诉我,诸如此类的原始类型int
没有方法。.getClass().getName()
在类型变量上使用int
并返回包装类“ Integer
”时,它如何工作?这是自动装箱的示例吗?
重要提示:仅在将int
变量传递到泛型类中时,这才对我有用。然后,从main方法调用泛型类中的方法。
我正在使用此通用类:
public class gen< T > {
private T thing;
public gen(T thing) {
this.thing = thing;
}
public String varType() {
return thing.getClass().getName();
}
}
public class Driver() {
int i = 5;
gen g = new gen(i);
System.out.println(g.getType());
}
输出为:java.lang.Integer
有人可以解释一下这个过程的内部原理吗?
这样的事情是行不通的:
public static void main(String args[]) {
int i = 5;
i.getClass().getName();
}
通用类型参数,例如T
,不能是基元。对于基本类型,请使用相应的包装器类。更具体地说,T
不能int
。
在您的情况下,编译器会在调用中为您自动将int
值装箱。Integer
new gen(i)
注1: gen
和new gen
是原始泛型,因为省略了type参数。不要使用原始泛型。此外,如果您仍然忽略它们又有什么意义呢?
注2: Java命名约定是为了使类名以大写字母开头,因此应命名类Gen
,而不是gen
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句