如何在Java中创建一个可以用多种类型调用的函数?
我的意思是这样的:如何在Java中创建一个可以用多种类型调用的函数?,java,function,class,Java,Function,Class,我的意思是这样的: function f(int a) { } function f(double a) { } function f(string a) { } 我想创建一个可以使用相同名称(f)和相同变量名称(a)调用的函数,但不能使用相同的类型(int,double等) 谢谢 您正在寻找泛型: 实例方法: public <T> void f(T a) { // T can be any type System.out.println(a); // test to
function f(int a) {
}
function f(double a) {
}
function f(string a) {
}
我想创建一个可以使用相同名称(f
)和相同变量名称(a
)调用的函数,但不能使用相同的类型(int
,double
等)
谢谢 您正在寻找泛型: 实例方法:
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..
}
int number = 10;
f(number);
String str = "hello world";
f(str);
char myChar = 'H';
f(myChar);
double floatNumber = 10.00;
f(floatNumber);
示例2:
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..
}
int number = 10;
f(number);
String str = "hello world";
f(str);
char myChar = 'H';
f(myChar);
double floatNumber = 10.00;
f(floatNumber);
示例3:
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..
}
int number = 10;
f(number);
String str = "hello world";
f(str);
char myChar = 'H';
f(myChar);
double floatNumber = 10.00;
f(floatNumber);
示例4:
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..
}
int number = 10;
f(number);
String str = "hello world";
f(str);
char myChar = 'H';
f(myChar);
double floatNumber = 10.00;
f(floatNumber);
和任何其他类型
进一步阅读
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!");
}
}
这就是所谓的重载方法,在Java中不能用关键字
function
来声明函数。如果打算将其作为返回类型,则类型名称应遵循Java命名约定。在Java中称为“方法”的函数必须是某个类型的成员,而您不会显示该类型。除此之外,你可以做你想做的事情,声明在不同类型上运行的函数的版本。函数声明中的变量名是占位符,由函数内部使用,但对其客户端没有命名要求。他们可能在寻找泛型。或者他们可能在寻找过载。或者他们可能正在寻找函数引用。或者他们可能正在寻找lambdas,这可能涉及泛型,但Java API中已有接口。@LewBloch我当然同意你的观点,但我不可能向他提出所有可能的想法。这个答案似乎就是我被问到这个问题时想到的。尽管如此,谢谢。@LewBloch,如果您有任何建议可以让答案更好,请随意编辑,如果我认为合适,我会接受。我认为只需将这些想法放在评论中,允许OP搜索它们并返回具体问题,在这里是最佳的,另外一些问题在其他答案中有介绍。@LewBloch,我明白了:)。