Pass parameter without specifying the type of the variable to receive in the function

6

I'm creating a function in Java that returns the type of the variable and as such, since I'm trying to figure out its type, I have no way of telling the function what type of variable to expect.

What I'm trying to build is the following:

public String getVarType(AnyType var){
    if (var instanceof ArrayList) {
        return "ArrayList";
    }
    if (var instanceof String) {
        return "String";
    }
}

How can I set the parameters for the function to expect any type?

    
asked by anonymous 12.01.2015 / 15:42

2 answers

12

If you are wanting to know the type of the object, work with Object . After all, every Java class is subclassed from Object implicitly. To check the object type, you can create a method for this:

public String getObjectName(Object o){
   return o.getClass().getSimpleName(); 
}

In which to be called will result in:

getObjectName(new ArrayList()); // ArrayList
getObjectName(new String()); //String

String abc = "abc";
getObjectName(abc); // String

There is one, however, if you try to use the above method with a int a = 10; variable, the return will be 10 . For what I researched, I can not get the primitive data type for obvious reasons.

If your application needs to do this comparison, you can work with numeric classes ( Integer to int , Double to double , etc ...), in those cases the above method would work. / p>

Integer integer = 10;
System.out.println(getObjectType(integer)); // Integer

Running on Repl.it

    
12.01.2015 / 15:52
1

You can do this.

public String getVarType(String var){
        return "String";
}
public String getVarType(ArrayList var){
       return "ArrayList";
}
    
12.01.2015 / 15:44