In Java, are there primitive types and arrays containing a package?

In Java, are there primitive types and arrays containing a package?

Probably not, but I just want to be sure.

+5
source share
4 answers

Simple answer

Let the test:

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

Conclusion:

null
null

No, they don’t do this :-)


Primitive types

Primitive classes are special constructions that do not have a package. For reference, see Source Long.TYPE, alias for 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");

As you can see, the primitive class is loaded through its own package and its own mechanism:

static native Class getPrimitiveClass(String name);

and discarded on Class<Long>(to enable auto-boxing, I think)

Wrapper types and their primitive types

BTW: - 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());
    }

}

:

: java.lang.Byte, :
: java.lang.Long, : long
: java.lang.Integer, : int
: java.lang.Short, :
: java.lang.Boolean, : boolean
: java.lang.Double, : double


Array.newInstance(type, length), :

private static native Object newArray(Class componentType, int length)
throws NegativeArraySizeException;

- , ( , -)

+17

, , .

: .

. - , .

+4

, , per se.

, , :

Integer.TYPE . .

, , ..

Integer.TYPE.getPackage()

null

+1
source

All Articles