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?

4
  • instanceof ... o.getClass() == Integer.getClass() .. just so you understand: int is a primitive, so that won't work. Commented Nov 8, 2017 at 9:30
  • 3
    if you need to check type of generic object, means it something wrong with our design. Commented Nov 8, 2017 at 9:39
  • Agreed with @user902383. If you need more control on your T generic definition, consider putting restriction such <T extends ...> in your method definition Commented Nov 8, 2017 at 9:41
  • You likely don't need generics at all, replace T with Number. Commented Nov 8, 2017 at 9:45

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

4 Comments

Integer.class (copy error); and of = Dutch for or ;)
... I didn't get it.
aNumber.getClass() == Integer.class
1 month later, I understood, thank you !
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.

Comments