【问题标题】:How do I create a function in Java, that can be called with many types?如何在 Java 中创建一个可以用多种类型调用的函数?
【发布时间】:2017-08-08 09:43:54
【问题描述】:

我的意思是这样的:

function f(int a) {

}
function f(double a) {

}
function f(string a) {

}

我想创建一个可以使用相同名称(f)和相同变量名称(a)但类型不同(intdouble 等)调用的函数

谢谢!

【问题讨论】:

  • 这就是你所说的重载方法。
  • 在 Java 中不能使用关键字 function 声明函数。如果打算将其用作返回类型,则类型名称应遵循 Java 命名约定。函数,在 Java 中称为“方法”,必须是您不显示的类型的成员。除此之外,你可以做你想做的事,声明在不同类型上运行的函数版本。
  • 函数声明中的变量名是占位符,由函数内部使用,但对其客户端没有命名要求。

标签: java function class


【解决方案1】:

您正在寻找泛型:

实例方法:

public <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
   // Do something..
}

类方法:

public static <T> void f(T a) { // T can be any type
    System.out.println(a); // test to see  `a` is printed
    // Do something..
}

假设这是在您的 main 方法中,您可以像这样调用类方法:

示例 1:

int number = 10;
f(number);

示例 2:

String str = "hello world";
f(str);

示例 3:

char myChar = 'H';
f(myChar);

示例 4:

double floatNumber = 10.00;
f(floatNumber);

以及任何其他类型。

进一步阅读Generics

Java Documentation of Generics

【讨论】:

  • 他们可能正在寻找仿制药。或者他们可能正在寻找超载。或者他们可能正在寻找函数引用。或者他们可能正在寻找 lambdas,这将涉及泛型,但对于 Java API 中已经存在的接口。
  • @LewBloch 我当然同意你的观点,但我不可能向他提出所有可能的想法。这个答案似乎是我在提出问题时想到的。不过谢谢。
  • @LewBloch 另外,如果您有任何建议可以使答案更好,请随时编辑它,如果我认为合适,我会接受。
  • 我认为只是将这些想法放在评论中并允许 OP 搜索它们并返回特定问题是最佳选择,而且其中一些已包含在其他答案中。
  • @LewBloch 我明白了:)。
【解决方案2】:

Java 类可以有同名的方法,但参数类型不同,正如您所要求的那样。

public class Foo {

    public void f(int a){
        System.out.println(a);
    }

    public void f(double a){
        System.out.println(a);
    }

    public void f(String a){
        System.out.println(a);
    }

    public static void main(String[] args) throws InterruptedException{
        Foo f = new Foo();
        f.f(9.0);
        f.f(3);
        f.f("Hello world!");
    }

}

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2017-05-26
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2018-06-08
    • 2014-06-17
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多