LongUtil { @SuppressWarnings("unchecked") public static <T extends Number> T cast(Long l, Class<T> targetClass) { requireNonNull(targetClass); if (l == null) { return null; } if (targetClass == Byte.class) { checkRange(l, Byte.MIN_VALUE, Byte.MAX_VALUE); return (T) (Byte) l.byteValue(); } else if (targetClass == Short.class) { checkRange(l, Short.MIN_VALUE, Short.MAX_VALUE); return (T) (Short) l.shortValue(); } else if (targetClass == Integer.class) { checkRange(l, Integer.MIN_VALUE, Integer.MAX_VALUE); return (T) (Integer) l.intValue(); } else if (targetClass == Long.class) { return (T) l; } else if (targetClass == Float.class) { return (T) (Float) l.floatValue(); } else if (targetClass == Double.class) { return (T) (Double) l.doubleValue(); } else if (targetClass == BigInteger.class) { return (T) BigInteger.valueOf(l); } else if (targetClass == BigDecimal.class) { return (T) BigDecimal.valueOf(l); } else if (targetClass == AtomicInteger.class) { checkRange(l, Integer.MIN_VALUE, Integer.MAX_VALUE); return (T) new AtomicInteger(l.intValue()); } else if (targetClass == AtomicLong.class) { return (T) new AtomicLong(l); } throw new IllegalArgumentException("Unable to cast Long to " + targetClass); } private  LongUtil(); @SuppressWarnings("unchecked") static T cast(Long l, Class<T> targetClass);  }
@Test void cast() { assertThrows(NullPointerException.class, () -> LongUtil.cast(1L ,null)); assertNull(LongUtil.cast(null, Long.class)); assertNotNull(LongUtil.cast(1L, Long.class)); assertCast(Byte.MIN_VALUE, Byte.MAX_VALUE, Byte.class); assertCast(Short.MIN_VALUE, Short.MAX_VALUE, Short.class); assertCast(Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.class); assertCast((long) Float.MIN_VALUE, (long) Float.MAX_VALUE, Float.class, false); assertCast((long) Double.MIN_VALUE, (long) Double.MAX_VALUE, Double.class, false); assertCast(Long.MIN_VALUE, Long.MAX_VALUE, BigInteger.class, false); assertCast(Long.MIN_VALUE, Long.MAX_VALUE, BigDecimal.class, false); assertCast(Integer.MIN_VALUE, Integer.MAX_VALUE, AtomicInteger.class); assertCast(Long.MIN_VALUE, Long.MAX_VALUE, AtomicLong.class, false); assertCast(1L, LongAdder.class, true); }