如何在Java中创建通用方法? [英] How to create a generic method in Java?
问题描述
我有以下方法:
pre $ public static void update(String name){
CustomTextType obj = findByName (名称);
...
}
我想使它成为一般使用方法,以便我不需要为每个新的自定义类型编写新的代码。我可以这样做,这将需要在调用update()之前实例化对象:
public static void update(String name,Object obj){
obj = findByName(name);
...
}
出于好奇,我想知道是否有一种方法可以用Java Generics来做到这一点:
//注意:这是一个例子,不起作用
public static void update(String name,< T> type){
type var = findByName(name);
...
}
有没有办法在Java中完成这个?
public static< T> void update(String name,T type){
//处理`T`的逻辑。
请注意 T
在这种情况下将是可证实的。或者 Foo
(它本身包含 Class
,可以从已经传入了instanceOfT.getClass()
)或 T
本身。
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():
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:
// 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?
public static <T> void update(String name, T type) {
//logic dealing with `T`.
}
Note that T
will be reifiable in this case. Either Foo<T>
(which itself includes Class<T>
that can be obtained from instanceOfT.getClass()
) or T
itself has been passed in.
这篇关于如何在Java中创建通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!