Convert a generic argument to int in java provided that it is a number

Here is what I tried to do, in a nutshell:

class example <T extends Number> { private int function(T number) { int x = (int) number; ... } ... } 

Basically, I'm trying to make T be a number, so I can convert it to int inside this function. The problem is that I get the error "incovertible types", so I have to do something wrong.

+4
source share
3 answers

Given that the abstract class Number is a superclass of the classes * BigDecimal , BigInteger , * Byte , Double , Float , * Integer , Long and Short ...

if you want to have an int view, you must use the .intValue() function.

If this is what you want to do.

+4
source

For your example, I don't think you need generics. I think you can simply:

 private int func(Number n) { return n.intValue(); } 

If you are trying to do something with generics, I would do it at the moment and first do the above work.

+3
source

Using

 x=number.intValue(); 
+1
source

All Articles