如何在 Java 中创建泛型方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18881144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:51:42  来源:igfitidea点击:

How to create a generic method in Java?

javagenerics

提问by TERACytE

I have the following method:

我有以下方法:

public static void update(String name) {
    CustomTextType obj = findByName(name);
    ...
}

I'd like to make it a general use method so that I don't need to write new code for every new custom type. I could do this, which would require instantiating the object before calling update():

我想让它成为一种通用方法,这样我就不需要为每个新的自定义类型编写新代码。我可以这样做,这需要在调用 update() 之前实例化对象:

public static void update(String name, Object obj) {
    obj = findByName(name);
    ...
}

Out of curiosity, I'm wondering if there is a way to do this using Java Generics:

出于好奇,我想知道是否有办法使用 Java 泛型来做到这一点:

// note: this is an example and does not work
public static void update(String name, <T> type) {
    type var = findByName(name);
    ...
}

Is there a way to accomplish this in Java?

有没有办法在 Java 中实现这一点?

采纳答案by nanofarad

public static <T> void update(String name, T type) {
    //logic dealing with `T`.
}

Note that Twill be reifiable in this case. Either Foo<T>(which itself includes Class<T>that can be obtained from instanceOfT.getClass()) or Titself has been passed in.

请注意,T在这种情况下,这将是可实现的。要么Foo<T>(它本身包括Class<T>可以从 中获得的instanceOfT.getClass())或者T它本身已经被传入。