【问题标题】:How to make method generic when using inheritance in Java?在Java中使用继承时如何使方法泛型?
【发布时间】:2022-01-21 01:35:54
【问题描述】:

我有 Employee 类和扩展 Employee 类的 3 个类。 我也有EmployeeService 接口,我希望只有一个save 方法来处理保存每种类型的员工。所以我认为它可以使用泛型来解决。 这是我在EmployeeService界面中尝试的:

public interface EmployeeService {
<SubRequestT extends  Employee>EmployeeResponse save(SubRequestT requestT);
}

以及提供实现的类:

@Service
public class EmployeeServiceImpl implements EmployeeService {

// So here in argument i want to have to put any kind of Employee, for example:
@Override
public EmployeeResponse save(OfficeEmployee requestT) {
// Logic for saving employee
    return null;
}
}

但是当我从 Employee 类型更改为任何其他类型时,例如从 Employee 扩展的 OfficeEmployee,编译器给我一个错误。解决这个问题的最佳方法是什么?

【问题讨论】:

  • 使用Employee有什么问题?

标签: java generics inheritance


【解决方案1】:

使用“方法泛型”我(我和编译器)也很挣扎,但使用“类型泛型”我们可以做到!

假设:

class Foo {/*...*/}

class Bar extends Foo {}

class Baz extends Foo {}

// extending your question to two generic parameters:
class FooResult {}

class BarResult extends FooResult {}

class BazResult extends FooResult {}

当我们定义我们的接口时:

interface FooI<I extends Foo, R extends FooResult> { //or with even more (fixed size) "generic parameters"
  R save(I request);
}

我们可以像这样覆盖它:

class BarImpl implements FooI<Bar, BarResult> {
  @Override
  public BarResult save(Bar bar) {
    // ...
    return ...;
  }
}

class BazImpl implements FooI<Baz, BazResult> {
  @Override
  public BazResult save(Baz baz) {
    // ...
    return ...;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多