简体   繁体   English

Java中的泛型方法

[英]Generics methods in Java

My question is: is it possible to make one generic method where I can use 2 different types? 我的问题是:是否有可能制作一种通用方法,我可以使用2种不同的类型? Eg an Integer and a String. 例如整数和字符串。

There is no practical use for this, but I'd just like to know if it's possible. 这没有实际用途,但我想知道它是否可行。 And if it is, how? 如果是的话,怎么样? :) :)

You dont need to use generics for this. 你不需要为此使用泛型。 You can overload the methods. 您可以重载方法。 For example 例如

public void method(Integer i){}

public void method(String s){}

If you call method with an integer then it will call the first method. 如果用一个整数调用方法,那么它将调用第一个方法。 If you call it with a string it will call the second method. 如果用字符串调用它,它将调用第二种方法。

Presumably you mean two different types of parameter? 大概你的意思是两种不同类型的参数?

You could use one method for the String param, and another than takes the integer and passes it on to the String version. 您可以对String参数使用一种方法,而另一种方法则使用整数并将其传递给String版本。

The example types are not good one as the are final. 示例类型不是好的,因为它们是最终的。 This mean that you can not use them to limit the generic parameter as nothing can inherit from them. 这意味着您不能使用它们来限制泛型参数,因为没有任何东西可以从它们继承。

So for that types the answer is No. 所以对于那些类型,答案是否定的。

But what we can do with Java is: 但是我们可以用Java做的是:

You can create a method that accept Object type. 您可以创建一个接受对象类型的方法。

 public <T> void doStaff(T obj) {

 }

You can create a method that is limited to CharSequence as String is final 您可以创建一个限制为CharSequence的方法,因为String是final

 public <T extends CharSequence> void doStaff(T str){ 

 } 

You can create a method that is litmited to more the one interface 您可以创建一个方法,使其更适合一个接口

public <T extends CharSequence & Comparable<T>> void doStaf(T interf) {

}

But even with so many possibilities we can not create a generic parameter that is valid for Two unrelated types. 但即使有这么多可能性,我们也无法创建一个对两个不相关类型有效的泛型参数。 This would not have sense. 这没有意义。 As main task of generic type is to provide type safety. 通用类型的主要任务是提供类型安全。 And in generally when we use them we should operate with interfaces not classes. 通常当我们使用它们时,我们应该使用接口而不是类。

If you want your method to accept Integer and String, try below approach: 如果您希望您的方法接受Integer和String,请尝试以下方法:

  public class Test {
public static void main(String[] a)  {
    method(new String(),new Integer("2"));
}
public static <T extends String, U extends Integer> void  method(T t, U u){

}
}

EDIT: 编辑:

if you want your method to take a single parameter that takes either a String or Integer 如果您希望您的方法采用一个带有String或Integer的参数

try this : 试试这个 :

public static <T extends Comparable<T>> void  method(T t){

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM