问题
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);
}
回答1:
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.
来源:https://stackoverflow.com/questions/29618425/how-implement-an-interface-generic-method