简体   繁体   中英

Implementing Callback Interface using 2 generic parameters in Java 6

// 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;
    }
 });

When I return Void type, above code compiles and works.

But I can't use Long as the return type. For example

logger = MetricLogger.getInstance(app);

// doesn't compile
logger.write(new Callback<LogFormat, Long>() {
    @Override
    public Long execute(LogFormat arg) {
        return null;
    }
});

The error message is,

Error:(66, 22) error: incompatible types: anonymous Callback <LogFormat,Long> cannot be converted to Callback<LogFormat,Void>

Java 6 doesn't support the generic return type?
Or am I missing something?

=================================================================

Updated

I found these code compile . But I can't sure which one is correct

// 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) { ... }
}

The write method on Logger class has probably a signature like : void write(Callback<? extends Object, Void> callback) which doesn't let you pass other than Void type

If it's your logger class implementation,you can change the signature, it should be something like void write(Callback<? extends Object, ? extends Object> callback) to let you use any type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM