typeOf without using getClass() or instanceof

3k views Asked by At

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")?

2

There are 2 answers

0
Tagir Valeev On BEST ANSWER

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

int x = 5;

Then x cannot be anything else other than int, so trying to do something like typeof(x) (like in some other languages) is meaningless.

You can generalize the variable type assigning it to the Object reference type:

int x = 5;
Object obj = x;

But even in this case obj will not be int. In this case Java compiler will automatically box your x to Integer type, so obj.getClass().getName() will return java.lang.Integer and obj instanceof Integer will return true.

0
Peter Lawrey 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