Home > Blockchain >  Java: Function parameter that takes any type
Java: Function parameter that takes any type

Time:03-17

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?

CodePudding user response:

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());
}

CodePudding user response:

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);
}

CodePudding user response:

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 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:

  • boolean will use the boolean method.
  • byte, short, int and long (all "whole number" integer values, as opposed to floating-point values) will use the long method.
  • float and double (floating-point) will use the double method.
  • Related