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

Asked

Viewed 2,053 times

5

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

What I’m trying to build is this:

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

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

2 answers

11


If you’re wondering what kind of object, work with Object. After all, every Java class is subclass of Object implicitly. To check the type of the object, you can create a method for this:

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

In which to be called he will mourn:

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

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

There is a however, if you try to use the above method with a variable int a = 10; the return will be 10. From what I’ve researched there’s no way to get the kind of primitive data for obvious reasons.

If your application needs to make this comparison, you can work with numerical classes (Integer for int, Double for double, etc...), in such cases the method mentioned above would work.

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

Running on Repl.it

1

You can do it like this.

public String getVarType(String var){
        return "String";
}
public String getVarType(ArrayList var){
       return "ArrayList";
}
  • I know, but this method can return a fatal error if I forget to validate some kind of variable. That’s why I’m resorting to if in order to have recourse to else

Browser other questions tagged

You are not signed in. Login or sign up in order to post.