0

Take for example this pseudocode:

public static<T> int findNumber(T xNumber, double a, int b){
    if (xNumber == int) {
        // do something... return some number...
    } else {
        return null; 
    }

Is there a way to express this in real functioning Java code?

kryger
  • 12,906
  • 8
  • 44
  • 65

2 Answers2

1

You cannot express this specific case using Java code.

You may find an answer here about the reasons.

However, if you wish to use generics with integers, the Integer Java class supports genericity. It also implements every basic operations (+ - * / %) used by native int. In your example, you may use:

if (xNumber instanceof Integer)

of even

if (xNumber.getClass() == Integer.getClass())

as suggested by @Stultuske in the comments.


EDIT: The commentaries about the design of your class are also very true. You may want to re-design your code, so you won't have to check for the type of your generic object (especially since you're checking for a single class type).

Yassine Badache
  • 1,810
  • 1
  • 19
  • 38
0

The class Number leads an almost hidden existence but is quite useful.

public static <T extends Number> int findNumber(...)
    ... xNumber.intValue() // longValue(), doubleValue()
    if (xNumber instanceof Integer) ...

Because of type erasure more is not feasible.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138