在java中返回通用接口实现类型的通用方法?

时间:2022-02-20 19:21:53

Can methods in java be used to return generics implementing a specified interface?

java中的方法可以用于返回实现指定接口的泛型吗?

You can do the following with abstract classes :

您可以使用抽象类执行以下操作:

 public <T extends myClass> T myFunct(T[] args){};

So I was wondering how you'd implement something like:

所以我想知道你是如何实现的:

 public <T implements myInterface> T myFunct(T[] args){};

1 个解决方案

#1


0  

Well nobody has answered so far but I figured you could create an abstract class that implements and interface and return a type that extends that abstract class.

到目前为止还没有人回答,但我想你可以创建一个抽象类来实现和接口并返回一个扩展该抽象类的类型。

 public abstract myAbstractClass implements myInterface{
      //in here you put interface methods
 }

then you'd be able to do things like

然后你就可以做类似的事情了

 public <T extends myAbstractClass> myFunct(T[] args){}

But if anyone has a better solution please post.

但如果有人有更好的解决方案,请发布。

#1


0  

Well nobody has answered so far but I figured you could create an abstract class that implements and interface and return a type that extends that abstract class.

到目前为止还没有人回答,但我想你可以创建一个抽象类来实现和接口并返回一个扩展该抽象类的类型。

 public abstract myAbstractClass implements myInterface{
      //in here you put interface methods
 }

then you'd be able to do things like

然后你就可以做类似的事情了

 public <T extends myAbstractClass> myFunct(T[] args){}

But if anyone has a better solution please post.

但如果有人有更好的解决方案,请发布。