【发布时间】:2016-04-23 13:45:45
【问题描述】:
我不明白为什么这段代码有错误。有什么建议吗?
谢谢
public class HelloWorld {
public static void main(String[] args) {
int choice = 2;
choice.className().getName();
}
}
【问题讨论】:
-
你能解释一下你要做什么吗?
我不明白为什么这段代码有错误。有什么建议吗?
谢谢
public class HelloWorld {
public static void main(String[] args) {
int choice = 2;
choice.className().getName();
}
}
【问题讨论】:
您不能在原始类型上调用 className()
【讨论】:
你不能,因为原语不是对象。
如果一个类的全名可用,则可以使用静态方法 Class.forName() 获取对应的 Class。这不能用于原始类型。
【讨论】:
您无法像那样确定原始变量数据类型。 代码应该如下所示。
public class HelloWorld {
public static void main(String[] args) {
int choice = 2;
String type = ((Object)choice).getClass().getName();
}
}
【讨论】:
你不能,因为它是原始类型,但你可以使用 Integer 代替 并检查它是否属于您可以使用的特定对象
Object temp = 1;
if(temp instanceof Integer){
System.out.println("Integer Object");
}
【讨论】: