在Java中,原始类型和数组是否包含包含?

Joh*_*oth 5 java arrays packages primitive-types

在Java中,原始类型和数组是否包含包含?

可能不是,但只是想确定.

Sea*_*oyd 17

简单的答案

我们来测试一下:

public static void main(final String[] args){
    System.out.println(long.class.getPackage());
    System.out.println(Object[].class.getPackage());
}
Run Code Online (Sandbox Code Playgroud)

输出:

null
null

不,他们没有:-)


原始类型

原始类是没有包的特殊构造.供参考,请参阅Long.TYPE以下别名的来源long.class:

/**
 * The <code>Class</code> instance representing the primitive type
 * <code>long</code>.
 *
 * @since   JDK1.1
 */
public static final Class<Long> TYPE =
       (Class<Long>) Class.getPrimitiveClass("long");
Run Code Online (Sandbox Code Playgroud)

如您所见,原始类通过包私有和本机机制加载:

static native Class getPrimitiveClass(String name);
Run Code Online (Sandbox Code Playgroud)

和铸造Class<Long>(为了启用自动拳击,我猜)

包装类型及其原始类型

BTW:每个包装类都有一个静态的final final字段,它被TYPE映射到相应的原始类,如下面的代码所示:

private static Class<?> getPrimitiveClass(final Class<?> wrapperClass){
    try{
        final Field field = wrapperClass.getDeclaredField("TYPE");
        final int modifiers = field.getModifiers();
        if(Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)
            && Modifier.isFinal(modifiers)
            && Class.class.equals(field.getType())){
            return (Class<?>) field.get(null);
        } else{
            throw new IllegalArgumentException("This is not a wrapper class: "
                + wrapperClass);
        }
    } catch(final NoSuchFieldException e){
        throw new IllegalArgumentException("This is not a wrapper class:"
            + wrapperClass + ", field TYPE doesn't exists.", e);
    } catch(final IllegalAccessException e){
        throw new IllegalArgumentException("This is not a wrapper class:"
            + wrapperClass + ", field TYPE can't be accessed.", e);
    }
}

public static void main(final String[] args){
    final List<Class<?>> wrappers =
        Arrays.<Class<?>> asList(
            Byte.class, Long.class, Integer.class,
            Short.class, Boolean.class, Double.class
            // etc.
        );
    for(final Class<?> clazz : wrappers){
        System.out.println("Wrapper type: " + clazz.getName()
            + ", primitive type: "
            + getPrimitiveClass(clazz).getCanonicalName());
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

包装类型:java.lang.Byte,原始类型:byte
包装器类型:java.lang.Long,基本类型:long
包装器类型:java.lang.Integer,基本类型:int
包装器类型:java.lang.Short,基本类型:short
Wrapper类型:java.lang.Boolean,primitive type:boolean
Wrapper类型:java.lang.Double,primitive类型:double


数组类型

可以通过Array.newInstance(type, length)内部调用此方法创建数组:

private static native Object newArray(Class componentType, int length)
throws NegativeArraySizeException;
Run Code Online (Sandbox Code Playgroud)

所以,类是由本机代码创建的特殊构造(并且它们没有包,否则你可以在某处找到它们)