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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With