1

Is there a Java method that determines if an instance of one Class<? extends Number> can be converted losslessly into an instance of another Class<? extends Number>?

Example method signature:

public static boolean canLosslessyConvert(Class<? extends Number> from, Class<? extends Number> to)

Examples of correct output:

canLosslessyConvert(Integer.class, Long.class)    == true
canLosslessyConvert(Long.class, Integer.class)    == false
canLosslessyConvert(Long.class, BigInteger.class) == true

A method in the Java 8 API is preferred, but if no such method exists, then methods in third-party libraries (like guava, spring, apache commons, etc.) are OK.

XDR
  • 4,070
  • 3
  • 30
  • 54
  • I don't thin such a method can exist in a common library. How would it know if a custom `MyNumber extends Number` could be converted losslessly to a long for example? – Tunaki Sep 04 '15 at 11:17
  • Hmm, that might prove hard. Depending on what you need that for you could try and approximate that, e.g. first determine whether the number is an integer or a decimal number. For integers you could compare the representable range, for decimal numbers you'd have to take precision into account but even then you might not be able to convert every float to a double without losses (again depending on how you define "lossless", see here for example: http://stackoverflow.com/questions/916081/convert-float-to-double-without-losing-precision) – Thomas Sep 04 '15 at 11:28

0 Answers0