Java 动态检查对象的类型

Java dynamically checking type of an object

我了解到 Java 的类型系统遵循一个错误的子类型化规则,因为它将数组视为协变。我在网上读到,如果一个方法的参数将被读取和修改,唯一的类型安全选项是不变性,这很有意义,我们可以在 Java 中提供一些简单的例子。

Java 通过动态类型检查正在存储的对象的类型来修补此规则在性能方面是否显着?我无法想象检查对象的类型会多出一两条额外的指令。一个后续问题是,忽略运行时的任何性能差异,这是否等同于对数组有一个未破坏的子类型化规则?如果我的问题很初级,请原谅我!

我发现一篇文章似乎可以回答您的问题:

"Java provides three different ways to find the type of object at runtime: instanceof keyword, getClass() and isInstance() method of java.lang.Class. Out of all three only getClass() is the one which exactly find Type of object while others also return true if Type of object is the super type."

由此看来,您应该能够编写 MyObject.getClass(),这将 return 对象 class。或者您可以使用 MyObject.isInstance(TheObject),如果 MyObject TheObject,这将 return 为真。第三,你应该能够:

if (MyObject instanceof TheObject) {
//your code
}

Here是link到网页

这里还有一个 link 到另一个 post 这可能有助于澄清:

Java isInstance vs instanceOf operator

还有另外两个 link 其他类似问题:

How to determine an object's class (in Java)?

java - How do I check if my object is of type of a given class?

性能始终是一个棘手的问题。根据上下文,此类检查可能会被完全优化掉。例如:

public static void main(String[] args){
    Object[] array = new String[2];
    array[0] = "Hello, World!";//compiler knows this is safe
    System.out.println(array[0]);
    array[1] = new Object();//compiler knows this will throw
}

在这里,编译器在两次赋值期间都可以访问数组的实际类型,因此 运行-time 检查并不是绝对必要的(如果编译器足够聪明,它可以优化它们) .

然而,在这个例子中,运行 次检查是必要的:

public static void main(String[] args){
    Object[] array = Math.random()<.5? new String[2]: new Object[2];
    array[0] = "Hello, World!";//compiler knows this is safe
    System.out.println(array[0]);
    array[1] = new Object();//compiler must check array type
}

当您考虑可能发生的令人费解的即时优化时,事情会变得更加复杂!尽管总的来说,是的,与 Java 的许多安全功能一样,也有必要的性能成本。它是否引人注目取决于您的用例。

至于等价问题:不,这与具有不变数组不同。不变数组会使 Object[] array = new String[2]; 成为编译时错误。