How implement an interface Generic Method

我怕爱的太早我们不能终老 提交于 2020-01-13 07:16:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!