【问题标题】:How can I execute method of an Object in Arraylist?如何在 Arraylist 中执行对象的方法?
【发布时间】:2021-12-29 08:47:55
【问题描述】:

我的问题是: 我创建了一个 Arraylist serviceList

service1 和 service2 都是来自 2 个类的 2 个独立对象,但它们具有相同的“执行”方法:

public Service1 service1;
public Service2 service2;

/*Then I add element to Arraylist:*/
serviceList.add(0, service1);
serviceList.add(1, service2);

/*then how can I run "excute" method of service1 and service2?
something like this:*/
for(Object service: serviceList){
    service.execute();
}

我尝试使用 ArrayList,但它是死路一条。 谢谢你的回答:D

【问题讨论】:

  • 您将它们声明为对象,对象不提供执行方法。所以要么你在你的循环中转换你的对象,要么你将它们声明为正确的类型

标签: java spring spring-boot spring-batch spring-batch-tasklet


【解决方案1】:

介绍一个接口:

interface Service {
  void execute();
}

class Service1 implements Service { ... }
class Service2 implements Service { ... }

List<Service> serviceList = ...

for (Service service: serviceList) {
  service.execute();
}

【讨论】:

  • 甚至不需要显式循环...serviceList.forEach(Service::execute)
【解决方案2】:

首先,ArrayList 只能接受声明的类型 T,所以你不能添加不同类型的对象,比如 K 到同一个 ArrayList 中。

解决方案 1
满足您需求的解决方案可能是声明 ArrayList&lt;Object&gt; list,然后添加这两个服务。

解决方案 2
现在,因为你想要一个通用的execute 方法,所以你的Service1Service2 类实现一些接口是很自然的,比如Service 为每个类实现一个唯一的execute 方法实现。你可以将你的 ArrayList 声明为ArrayList&lt;Service&gt; list

【讨论】:

    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2021-02-01
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    相关资源
    最近更新 更多