【问题标题】:Anonymous method is using generics values as perameter匿名方法使用泛型值作为参数
【发布时间】:2013-02-19 20:57:46
【问题描述】:

我坚持使用匿名方法的 Java 传统, 我正在使用具有通用接口的第三方库,该接口将 table_name 作为其通用类型

喜欢

TableQueryCallback<WYF_Brands> =new TableQueryCallback<WYF_Brands>() {
    @Override
    public void onCompleted(List<WYF_Brands> arg0, int arg1,
        Exception arg2, ServiceFilterResponse arg3) {
        // TODO Auto-generated method stub
    }
};

这里 WYF_Brands 是我的表名。

我想要的是

TableQueryCallback<WYF_Users> =new TableQueryCallback<WYF_Users>() {
    @Override
    public void onCompleted(List<WYF_Users> arg0, int arg1,
        Exception arg2, ServiceFilterResponse arg3) {
        // TODO Auto-generated method stub
    }
};

WYF_Users 是我的另一个表。

要求:我想以可重复使用的方式对我的所有表使用这种方法。

我在数据库中有许多表,不会为不同的表创建不同的方法。我不知道如何使用可以接受任何表名作为参数的泛型。

另一件事是这个接口是第三方库的一部分,所以我无法更改它,因为它在可执行 jar 文件中。

我正在使用 java 作为编程语言。

【问题讨论】:

  • TableQueryCallback 构造函数的签名是什么?
  • 您的 WYF_* 对象是否通过继承共享一个共同的祖先(对象除外)? onCompleted方法中你要做什么处理?
  • @OldCurmudgeon 我假设TableQueryCallback 是一个接口,因此没有构造函数。
  • @OldCurmudgeon:我不知道签名是什么,因为我使用的是第三方库,它只有可执行的 jar 文件。
  • @benzonico:实际上不,它们是代表我数据库中不同表的简单类。如果你想要声明,我可以发布一个。

标签: java generics anonymous-types anonymous-methods


【解决方案1】:

听起来你只想要一个通用方法:

public <T> TableQueryCallback<T> createTableQueryCallback() {
    return new TableQueryCallback<T>() {
        @Override
        public void onCompleted(List<T> list, int arg1,
                Exception arg2, ServiceFilterResponse arg3) {
            // I'm assuming the implementation here would be the same each time?
        }
    };
}

虽然我很想创建一个 named 嵌套类来代替:

private static SomeSpecificTableQueryCallback<T> implements TableQueryCallback<T> {
    @Override
    public void onCompleted(List<T> list, int arg1,
            Exception arg2, ServiceFilterResponse arg3) {
        // I'm assuming the implementation here would be the same each time?
    }
}

...我不明白为什么将其设为匿名会在这里为您带来任何好处。

【讨论】:

    【解决方案2】:

    我假设您有 WYF_BrandsWYF_Users 和所有其他表的通用基类/接口。让它成为WYF_Base。我还假设这个基类/接口足以让您实现常用方法。如果是这样,那么您可以像这样实现一次方法:

    public class CommonTableQueryCallback <T extends WYF_Base>
        implements TableQueryCallback <T>
    {
        @Override
        public void onCompleted(List <T> list, int n,
            Exception exception, ServiceFilterResponse response) {
            // Implement your logic here.
            // All elements of `list` are guaranteed to extend/implement WYF_Base
            // And compiler knows this!
    
            WYF_Base e = list.get (0); // This is correct!
        }
    }
    

    然后你可以像下面这样使用这个类:

    TableQueryCallback <WYF_Brands> callback = 
        new CommonTableQueryCallback <WYF_Brands> ();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2010-11-03
      • 2015-03-30
      相关资源
      最近更新 更多