'Java: Function parameter that takes any type
Im writing a Java function to output things to the console with a certain format, but I need one of the parameters to accept any type as an argument. How do i do this?
Solution 1:[1]
Using Generics, it would work as follows:
public static <T> void printAnything(T anything){
System.out.println(anything);
}
public static void main(String[] args){
printAnything(new SyncPart());
}
Solution 2:[2]
The generics shown in SMA's answer are unnecessary: just take Object as your parameter type:
public static void printAnything(Object anything){
System.out.println(anything);
}
Solution 3:[3]
Any type is not possible. Primitives will stop you from what you're doing.
But you can use void myFunction(Object anyObject) {} for example, and give it any Class-type = reference-type Object.
If you still wanna include primitives, you have to split up to multiple methods:
package stackoverflow;
public class ClassOverload {
// central method
static public void myMethod(final Object pObject) {
final String type = pObject == null ? null : pObject.getClass().getSimpleName();
System.out.println("ClassOverload.myMethod(" + pObject + ") of type " + type);
}
// primitive overloading methods
static public void myMethod(final boolean pValue) { // absolutely needed
myMethod(Boolean.valueOf(pValue));
}
static public void myMethod(final char pValue) { // absolutely needed
myMethod(Character.valueOf(pValue));
}
static public void myMethod(final byte pValue) {
myMethod(Byte.valueOf(pValue));
}
static public void myMethod(final short pValue) {
myMethod(Short.valueOf(pValue));
}
static public void myMethod(final int pValue) {
myMethod(Integer.valueOf(pValue));
}
static public void myMethod(final long pValue) { // absolutely needed
myMethod(Long.valueOf(pValue));
}
static public void myMethod(final float pValue) {
myMethod(Float.valueOf(pValue));
}
static public void myMethod(final double pValue) { // absolutely needed
myMethod(Double.valueOf(pValue));
}
}
This will convert your primitives to their reference type and keep the type as close to the original as possible.
If you wanna reduce the methods, you could just keep the boolean, long and double methods. All other primitives can be cast into one of those three:
booleanwill use thebooleanmethod.charwill use thecharmethod.byte,short,intandlong(all "whole number" integer values, as opposed to floating-point values) will use thelongmethod.floatanddouble(floating-point) will use thedoublemethod.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JCompetence |
| Solution 2 | Andy Turner |
| Solution 3 |
