is it possible check the primitive type of a numeric value in Java 11?
Let's say I have a method
@Test
public void test1(){
short x = 10;
short y = 3;
var z = x * y // z is of int type
}
@Test
public void test1(){
short x = 10;
short y = 3;
var z = (short)x * y // z is of int type as variables are promoted
}
@Test
public void test3(){
short x = 10;
short y = 3;
var z = (short)x * (short)y // is z of primitive type short? Is there
// any way to check the type if it is short, long, int...
// I.e z instanceof ... or something similar specifically for
// primitive types?
}
There isn't a direct way to test the type of a variable or a primitive value in Java. However you can do it indirectly by exploiting method overload resolution.
Write yourself some overloaded methods like this:
public String typeOf(short arg) { return "short"; }
public String typeOf(int arg) { return "int"; }
public String typeOf(long arg) { return "long"; }
Then use them like this:
public void test1(){
short x = 10;
short y = 3;
var z = x * y;
System.out.println(typeOf(z)); // in this case "int" will be printed.
}
and so on.
However this is unnecessary. The JLS specifies what the type of z
will be in each case. The answer will be int
in each of those cases.
The operands of a *
will be promoted to int
or long
, and the result will be int
or long
. In your second and third examples, the cast to short
makes no difference 1 .
The only way that you will get z
to be short
is to do the cast after the multiplication; ie
z = (short)(x * y);
1 - In these cases. It would make a difference if the casts caused truncation of the significant bits; eg if x
or y
were int
etcetera.
There's no way to check that at runtime, because the type is fixed at compile time. Even though you defined your variables using var
: the type is still fixed at compile time (and depends on the type of the expression used to initialize it).
In all three of your examples z
is of type int
, because a multiplication of two any numbers of type byte
, char
or int
will always result in an int
result and you only ever cast the inputs , but never the outputs.
If you wanted var z
to be of type short
, then you'd need to cast the result of the calculation like this:
var z = (short) (x*y);
But if the type of z
is actually important, then I'd avoid var
and explicitly state the type anyway:
short z = (short) (x*y);
You can use method overloading which lets you call the same function name and run custom to the data type or number of parameters in the method.
class Type{
String getType(short val){
return "short";
}
String getType(int val){
return "int";
}
String getType(long val){
return "long";
}
{
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.