是否可以将任何类型的输入传递给方法并确定给出的输入类型?

Is it possible to pass input of any kind to a method and determine what type of input is given?

是否可以将任何类型的输入发送到方法并在对传递的类型进行操作时找到类型?

like

public methodName(int value){....}

而不是这个

public methodName(anyType anValue){....}

我正在使用 java 8.

你可以做的 "best" 是传入一个 Object。然后您可以检查它以找出它是什么(除非它是 null,那么您不知道它应该是什么,如果这很重要的话)。

if (theObject instanceof String){
   // do something
} else if (theObject instanceof Number){
   // do something
}

但这有点违背了强类型语言的目的,而且很少适用。

您还会丢失任何泛型类型信息(因为它在运行时被删除,仅在编译时可用)。

作为替代方案,考虑提供具有不同参数类型的方法的多个重载。

是的,您可以使用泛型编程来做到这一点。查看 here 以获取有关如何使用 Java.

的泛型编程的更多信息

您可以使用通用方法,例如

public static <T> void exampleMethod(T obj) {
    System.out.printf("%s %s%n", obj.getClass().getName(), obj);
}

然后您可以将任何 Object 类型传递给 exampleMethod(或具有自动装箱功能的 primitive)。例如,

public static void main(String args[]) {
    exampleMethod("Hello");
    exampleMethod(123);
    exampleMethod(123.123f);
}

输出

java.lang.String Hello
java.lang.Integer 123
java.lang.Float 123.123

可以利用 instanceof

public void methodName(Object value){
        if(value instanceof Integer){

        }else if(value instanceof String){

        }

}