如何制作接受任何类型变量的 Java 函数? [英] How can I make a Java function that accepts any type of variable?

查看:38
本文介绍了如何制作接受任何类型变量的 Java 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个可以接受任何传入变量的函数,无论类型如何(intdoubleString 或其他对象),然后可能确定变量的类型并根据类型进行有条件的操作.

我该怎么做?

解决方案

重载是最推荐的选项,大多数时候你不需要接受任何类型变量的函数. >

但是一个接受任何Object的函数呢?您可能需要使用 instanceof 并根据数据类型处理它们.

instanceof 的用法:[对象实例的名称] instanceof [要匹配的对象类型的名称]

instanceof 返回一个 boolean: true 当且仅当对象实例的类型与要匹配的类型相匹配.

接受任何变量类型"的函数或方法的一个示例:

public static void method(Object obj) {if (obj instanceof String)System.out.println("我是一个字符串!");if (obj instanceof Integer)System.out.println("我是一个整数!");//其他类型的对象也类似if (obj instanceof ... )...//.getClass() 适用于任何对象System.out.println(obj.getClass());}

请注意,不建议制作接受任何类型变量的函数.

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.

这篇关于如何制作接受任何类型变量的 Java 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆