I am currently trying to use System.out.print to give out the type out of an integer x. However from what I've found the only functions simular to typeOf are getClass, which does not work on int, or instanceof, which seems to only work with an if. Is there any other command I could try or am I stuck with System.out.print("Integer")
?
typeOf without using getClass() or instanceof
2.9k views Asked by byj At
2
There are 2 answers
0
On
Generally, there is no sane reason to do this if you know the type, you don't need a function to work it out for you.
The only time this is useful is when you can't work out the type, e.g. because you are learning and the type is not obvious. You can implement this using an overloaded function like this.
public static void main(String[] args) {
byte b = 1;
byte a = 2;
System.out.println("The type of a+b is "+typeOf(a+b));
long l = 1;
float f = 2;
System.out.println("The type of l+f is "+typeOf(l+f));
}
public static String typeOf(byte b) {
return "byte";
}
public static String typeOf(char ch) {
return "char";
}
public static String typeOf(short s) {
return "short";
}
public static String typeOf(int i) {
return "int";
}
public static String typeOf(long i) {
return "long";
}
public static String typeOf(float i) {
return "float";
}
public static String typeOf(double i) {
return "double";
}
public static String typeOf(boolean b) {
return "boolean";
}
public static String typeOf(Object o) {
return o.getClass().getName();
}
prints
The type of a+b is int
The type of l+f is float
Note that Java is statically typed language. There's no need to check the variable primitive type at runtime, because it's known at compile time and cannot change. For example, if you declare
Then
x
cannot be anything else other thanint
, so trying to do something liketypeof(x)
(like in some other languages) is meaningless.You can generalize the variable type assigning it to the
Object
reference type:But even in this case
obj
will not beint
. In this case Java compiler will automatically box yourx
toInteger
type, soobj.getClass().getName()
will returnjava.lang.Integer
andobj instanceof Integer
will return true.