如何实现接口通用方法 [英] How implement an interface Generic Method
问题描述
我如何实现一个字符串类型的非泛型接口
,并带有泛型方法
以下是界面:
// non-泛型类
接口I {
public< T> T doI(T t);
这个接口中的< T>
意味着传递给该方法的类型 T
与类型<
实现需要使用符号T,就好像它是一个类一样。
code> T p> public< T> T doI(T t){
Object a = t.getClass()。newInstance();
return(T)a;
$ / code>
然后你可以用类似于
I obj = getIImplementer();
String a = obj.doI(ssssssss);
编译器知道它可以从传入的对象类型推断返回类型。
如果你想实现一个特定的版本,你需要将泛型参数放在接口上而不是方法中,这样你可以输入实现类以及方法参数。 b $ b
How can I implement, for example, a String type of a non-generic-interface
with a generic method
?
Here is the interface:
// non-generic-class
interface I{
public <T> T doI(T t);
}
All the <T>
in this interface means is that the type T
passed to the method is the same as the type T
returned from the method.
Implementation requires some use of the symbol T as if it was a class Like
public <T> T doI(T t){
Object a = t.getClass().newInstance();
return (T) a;
}
You can then call it with something like
I obj = getIImplementer ();
String a = obj.doI ("ssssssss");
And the compiler knows it can infer the return type from the object type passed.
If you want to implement a specific version you need to put the generic parameter on the interface rather than the method so you can type the implementing class and therefore the method parameter.
这篇关于如何实现接口通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!