isAbstract() 修饰符返回不正确的结果 - 为什么?

isAbstract() Modifier returning Incorrect result - Why?

根据我的理解,下面的代码应该打印 False 作为输出

但是,当我 运行 这段代码时,它正在打印 True 作为输出。

来自 Java 文档:

Return true if the integer argument includes the abstract modifier, false otherwise.

public class Test{
    public static void main(String[] args) {
        System.out.println(Modifier.isAbstract(byte[].class.getModifiers())); 
    }
}

有人可以帮助我理解这种行为吗?

可以在 JLS 中找到对此行为的提示,10.8. Class Objects for Arrays:

Every array has an associated Class object, shared with all other arrays with the same component type.

Although an array type is not a class, the Class object of every array acts as if: [snipped]

根据这个推理,数组不是“真实的”class,因此它绝对不是具体的class。同样的逻辑也适用于 int.class 被认为是抽象的。

我的解释是,数组被认为是 abstract 因为它们是由 JVM 本身实例化的。

There just exists no concrete class for any array type.

一个数组有一个 contract defined by the JLS :

  1. 索引可访问性
  2. CloneableSerializable
  3. 的实施

但是除了语言本身,没有人可以实现这些,因为我们自己无法真正声明一个实现。

Javadoc of int java.lang.Class.getModifiers() 指定数组类型的一些修饰符应该 returned 什么(例如,final 修饰符需要是 trueinterface 修饰符必须是 false)。另一方面,它没有指定 abstractstatic 修饰符应该用于数组类型,这意味着决定 return truefalse 未记录在 JDK 中。因此,任何实现都可以选择 return truefalse

int java.lang.Class.getModifiers()

Returns the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine's constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier.

If the underlying class is an array class, then its public, private and protected modifiers are the same as those of its component type. If this Class represents a primitive type or void, its public modifier is always true, and its protected and private modifiers are always false. If this object represents an array class, a primitive type or void, then its final modifier is always true and its interface modifier is always false. The values of its other modifiers are not determined by this specification.

The modifier encodings are defined in The Java Virtual Machine Specification, table 4.1.

根据我的理解,getModifier() 的 java 语言规范是:

If the underlying class is an array class, then its public, private and protected modifiers are the same as those of its component type. If this Class represents a primitive type or void, its public modifier is always true, and its protected and private modifiers are always false

现在,它的其他修饰符的值不由本规范确定,例如摘要.

来自 JVMS Table 4.1-A:

ACC_ABSTRACT 0x0400 声明摘要;不得实例化。

abstract的定义说:

An abstract class is a class that is incomplete, or to be considered incomplete.

如果有像[]这样的纯数组那么它确实不完整,因为没有提供组件类型。

这将违反 15.10.1. Array Creation Expressions 的规范:

It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type.

它不仅表示可具体化的类型,而且根本不是类型。因此不可能创建 [] 的实例——就像抽象 类.

因为没有纯数组[]这只是一种推测。此外,返回了 byte[] 的修饰符。它仍然是 .

显示的规格