在接口中使用泛型方法没有意义吗? [英] It does not make sense to have generic method in interface?

查看:773
本文介绍了在接口中使用泛型方法没有意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些功能强大的编程代码。我有一个接口和一个具有以param的形式实现该接口的函数。

  public interface Statement 
{
T executeTStatement();
}

public class StatementExecutor
{

public static< T> T executeStatement(语句声明)
{
结果;
尝试
{


result = statement.executeStatement();


}
catch .....
finally ....

返回结果;





所以StatementExecutor类和executeStatment函数在类中是没有问题的,因为executeStament声明为静态,并且不需要在类声明中。但是因为static是接口方法的非法修饰符,所以在接口中不能做到这一点,我只能添加到接口声明中,并且我想避免它,因为在该接口中只有一个泛型方法。
所以问题是,如果我遇到这种情况,在我的设计中出现了问题,或者它只是限制了Java?是否有一些技巧在接口中声明泛型方法而不在接口级声明它?

你可以声明泛型方法在你的界面中是这样的:

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

但是这样做没什么意义 - 你有一个方法返回一个东西,但什么时候会定义什么?因此,T必须以某种方式被绑定以用于任何用途:


  • 在接口级声明它,并且必须绑定T定义你的引用(但你不想这样做)

  • 从方法的一些参数中推导出类型T:

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



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 ?

解决方案

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);
    }   
    

这篇关于在接口中使用泛型方法没有意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆