在下面的代码段中,我想知道为什么var.get("key").getClass()
返回java.lang.Integer
而不是java.lang.Object
,因为方法的参数var
的类型为{ {1}}:
Map<String, Object>
答案 0 :(得分:4)
这正是它应该如何。
getClass()
返回实际的运行时对象类,如javadoc所说:
/**
* Returns the runtime class of this {@code Object}. The returned
* {@code Class} object is the object that is locked by {@code
* static synchronized} methods of the represented class.
*
* <p><b>The actual result type is {@code Class<? extends |X|>}
* where {@code |X|} is the erasure of the static type of the
* expression on which {@code getClass} is called.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
public final native Class<?> getClass();
另一个例子是:
Object o = 1;
System.out.println(o.getClass());
输出:
class java.lang.Integer
引用的类型为Object
,运行时对象的类型为Integer
。
使用接口引用类型时的相同情况:
List<Integer> list = new ArrayList<>();
System.out.println(list.getClass());
输出:
class java.util.ArrayList
此处的引用类型为List
,但它是一个没有实现的接口。这里的实际运行时对象是ArraysList
。