【发布时间】:2015-11-26 12:05:01
【问题描述】:
// interface
public interface Callback<T, R> {
R execute(T arg);
}
// application code
logger = MetricLogger.getInstance(app);
logger.write(new Callback<LogFormat, Void>() {
@Override
public Void execute(LogFormat arg) {
// do something
return null;
}
});
当我返回 Void 类型时,上面的代码编译并工作。
但我不能使用Long 作为返回类型。例如
logger = MetricLogger.getInstance(app);
// doesn't compile
logger.write(new Callback<LogFormat, Long>() {
@Override
public Long execute(LogFormat arg) {
return null;
}
});
错误信息是,
错误:(66, 22) 错误:不兼容的类型:匿名
Callback <LogFormat,Long>无法转换为Callback<LogFormat,Void>
Java 6 不支持泛型返回类型?
还是我错过了什么?
================================================ ===================
更新
我找到了这些代码编译。但我不确定哪个是正确的
// Solution 1
public interface Callback<T> {
<R> R execute(T arg)
}
new Callback<LogFormat>() {
@Override
public Long execute(LogFormat arg) { ... }
}
// Solution 2
public interface Callback {
<T, R> R execute(T arg)
}
new Callback<LogFormat>() {
@Override
public <LogFormat, Long> Long execute(LogFormat arg) { ... }
}
【问题讨论】:
-
logger.write() 方法似乎只接受 Callback
。此外,提供的代码似乎与提供的错误不匹配:Callback VS Callback -
@Mikey,你编译代码了吗?
-
不 - 我不知道 MetricLogger 来自哪里:请参阅 Prims 答案
-
我认为 Prims 的回答是正确的:正确的解决方案取决于使用情况。
标签: java function generics interface callback