It does not make sense to have generic method in interface?

谁说胖子不能爱 提交于 2019-12-13 06:00:37

问题


I'm writing a little functional programming piece of code. I have an interface, and a class which has a function that gets an implementation of that interface as a param.

  public interface Statement
  {
      T executeTStatement();
  }   

  public class StatementExecutor 
  {

    public static<T> T executeStatement(Statement statement)
    {
         T result;
         try
         {            
             .
             .
             result = statement.executeStatement();
             .
             .
         }
         catch.....
         finally....

         return result;

    }
  }

So the StatementExecutor class and executeStatment function in class are fine, since executeStament declared with static and does not require to have in class declaration. But since static is an illegal modifier for the interface method, the same cannot be done in the interface, I only can add to interface declaration, and I want avoid it cause there will be only one generic method in that interface. So the question is, if I get to such situation there something wrong in my design, or it just limitation of java ? And is there some trick to declare generic method in interface without declaring it on interface level ?


回答1:


You can declare generic methods in your interface like this:

public interface Statement
{
    <T> T executeTStatement();
}   

But in this way it doesn't make to much sense - you have a method that returns a "something", but when will "something" be defined? So T has to be bound in some way to be of any use:

  • declare it at the Interface-Level and have to bind T when defining your reference (but you didn't want to do that)
  • deduce the type T from some argument to the method:

    public interface Statement
    {
        <T> T executeTStatement(T argument);
    }   
    



回答2:


David, generally speaking a java interface is a Object Oriented "prototype" for a real object implementation. "Static mathod" are not (properly) Object Oriented, then static method are not allowed on interface.

Let me say "Static method" and "Java interface" are incompatible (please accept my lack of formalism).

Finally the sentence

is there some trick to declare generic method in interface without declaring it on interface level ?

is a little bit controversial, please refine it.



来源:https://stackoverflow.com/questions/20989740/it-does-not-make-sense-to-have-generic-method-in-interface

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