Java generics and the Number class

Viewed 17631

I want to create a method that compares a number but can have an input that is any of the subclasses of Number.

I have looked at doing this in the following manner...

public static <T extends Number> void evaluate(T inputNumber) {
  if (inputNumber >= x) {
    ...
  }
}

I need to get the actual primative before I can perform the comparison, the Number class has methods to retrieve this for each primative but I want a clean way of selecting the correct one.

Is this possible?

Cheers

6 Answers

There's always an option to work with unknown data with pattern interfaces. That's how sorts works with Comparator interface. You should create and add as method parameter functional interface Evaluator with evaluate(T number) method and determine evaluation logic out of method. You can also create some examples from helper classes, like Evaluators::IntegerEvaluator which will work for Integers and suggest them to the client. Sry for my eng

Related