【发布时间】:2012-05-18 21:05:24
【问题描述】:
可能重复:
How to determine an object's class (in Java)?
Java determine which class an object is
我有以下示例不完整的方法来比较给定对象的对象类型
public void test(Object value) {
if (value.getClass() == Integer) {
System.out.println("This is an Integer");
}else if(value.getClass() == String){
System.out.println("This is a String");
}else if(value.getClass() == Float){
System.out.println("This is a Float");
}
}
方法可以这样调用:
test("Test");
test(12);
test(10.5f);
此方法实际上不起作用,请帮助我使其起作用
【问题讨论】:
-
我最喜欢的问题类型。预计 30 秒内有 45 个答案。
-
使用
instanceof运算符。If (value instanceof Integer){