gpt4 book ai didi

Java 继承 - 尝试创建通用方法从 Guava EventBus 库获取总线

转载 作者:行者123 更新时间:2023-12-01 12:43:12 25 4
gpt4 key购买 nike

已关注 this answer我正在尝试创建一个从 Guava EventBus 库创建 EventBusAsyncEventBus 的库。

因此,我尝试创建一个扩展 Guava 的 AsyncEventBusClass 的类,因此我创建了 RetroAsyncEventBus,如下所示:

public class RetroAsyncEventBus extends AsyncEventBus{

private AsyncEventBus asyncEventBus;

public RetroAsyncEventBus(Executor executor) {
super(executor);
}

@Override
public void register(Object object) {
super.register(object);
}

@Override
public void unregister(Object object) {
super.unregister(object);
}
}

首先,我不明白为什么我必须覆盖 注册取消注册,根据我对继承的理解,我应该能够通过 RetroAsyncEventBus 对象访问这个 super 方法,我的意思是我应该能够做到这一点:

RetroAsyncEventBus retroAsyncEventBus = new RetroAsyncEventBus(executor);
retroAsyncEventBus.register(this);

但是我的 IDE (netbeans) 说我不能,因为编译错误:retroAsyncEventBus.register(this); 找不到符号。所以我必须覆盖它们,我可以接受这一点。

然后我有我的 RetroBus 类,我可以在其中以 singleton 方法创建并初始化我想要的总线。像这样:

public class RetroBus {

private final EventBus bus;
private final AsyncEventBus asyncEventBusMainThread;
private final AsyncEventBus asyncEventBus;
private static RetroBus instance;

private RetroBus(){
bus = new EventBus();
asyncEventBusMainThread = new AsyncEventBus(new EventQueueExecutor());
asyncEventBus = new AsyncEventBus(Executors.newCachedThreadPool());
}

public synchronized static EventBus getDefaultBus()
{
if (instance == null)
{
instance = new RetroBus();
return instance.getDefaultEventBus();
}
return instance.getDefaultEventBus();
}

public synchronized static AsyncEventBus getAsyncBus()
{
if(instance == null)
{
instance = new RetroBus();
return instance.getAsyncEventBus();
}
return instance.getAsyncEventBus();
}

public synchronized static AsyncEventBus getAsyncBusToMainThread()
{
if(instance == null)
{
instance = new RetroBus();
return instance.getAsyncEventBusMainThread();
}
return instance.getAsyncEventBusMainThread();
}

private EventBus getDefaultEventBus() {
return this.bus;
}

private AsyncEventBus getAsyncEventBus() {
return this.asyncEventBus;
}

private AsyncEventBus getAsyncEventBusMainThread() {
return this.asyncEventBusMainThread;
}
}

现在我的库编译得很好。在我要测试的项目中,我导入我的库,然后尝试执行以下操作:

public class TestClass {

private RetroAsyncEventBus retroAsyncEventBus;

public TestClass() {

retroAsyncEventBus = (RetroAsyncEventBus) RetroBus.getAsyncBusToMainThread();
retroAsyncEventBus.register(this);
}
}

这就是我真正的问题出现的地方。首先,它迫使我强制转换 RetroBus.getAsyncBusToMainThread(); 并且我不明白为什么我在 时被迫强制转换它RetroAsyncEventBus extends AsyncEventBus 所以它们应该是相同的类型,对吗?

然后,如果我像我一样对其进行强制转换,则会收到此编译错误: getAsyncBusToMainThread() 的类型;是错误的。

有人可以解释一下我在这里做错了什么吗?

最佳答案

您必须强制转换的原因是因为您的方法返回的是 AsyncEventBus 而不是 RetroAsyncEventBus。这意味着程序必须使用该方法返回的任何可能的 AsyncEventBus 对象。

更改返回类型,您将不再需要强制转换。

关于Java 继承 - 尝试创建通用方法从 Guava EventBus 库获取总线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24895544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com