Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a Java function that accepts any type of variable?

Tags:

I would like to make a function that can accept any incoming variable, regardless of type (int, double, String or other objects), and then possibly determine the type of variable and act conditionally on the type.

How can I do this?

like image 272
genisome Avatar asked May 14 '18 22:05

genisome


1 Answers

Overloading is the most recommended option, most of the time you do not need a function that accepts any type of variable.

But what about a function that accepts any Object? You may need to use instanceof and handle them depending of the data type.

Usage of instanceof: [Name of object instance] instanceof [Name of object type to match]

instanceof returns a boolean: true if and only if type of object instance matches the type to match.

One example of a function or method that accepts "any variable type:"

public static void method(Object obj) {
    if (obj instanceof String)
        System.out.println("I am a String!");

    if (obj instanceof Integer)
        System.out.println("I am an Integer!");

    // Similarly for other types of Object
    if (obj instanceof ... )
        ...

    // The .getClass() is for any Object
    System.out.println(obj.getClass());
}

Please note that making a function that accepts any type of variable is not recommended.

like image 52
Ṃųỻịgǻňạcểơửṩ Avatar answered Sep 28 '22 16:09

Ṃųỻịgǻňạcểơửṩ