2008-10-16 16 views

risposta

23

C'è un metodo sull'oggetto Class, isPrimitive.

+0

Ah, non ho visto questo. Grazie. – nathan

1

Questo metodo sarà anche verificare se si tratta di un wrapper di un tipo primitivo così:

/** 
* Checks first whether it is primitive and then whether it's wrapper is a primitive wrapper. Returns true 
* if either is true 
* 
* @param c 
* @return whether it's a primitive type itself or it's a wrapper for a primitive type 
*/ 
public static boolean isPrimitive(Class c) { 
    if (c.isPrimitive()) { 
    return true; 
    } else if (c == Byte.class 
      || c == Short.class 
      || c == Integer.class 
      || c == Long.class 
      || c == Float.class 
      || c == Double.class 
      || c == Boolean.class 
      || c == Character.class) { 
    return true; 
    } else { 
    return false; 
    } 
+0

Usa Number.class.isAssignableFrom (c) invece di controllare l'uguaglianza con tutti i sottotipi di Numero –

+0

@digitalillusion Che includerebbe anche tipi non wrapper come 'BigInteger', che è un' Numero' troppo – Kapep

+0

'return c.isPrimitive() | | c.getSuperclass() == Number.class || c == Boolean.class || c == Character.class; 'è una soluzione più semplice –

Problemi correlati