(in file Processor.java:)
public interface Processor
{
Runner<? extends Processor> getRunner();
}
(in file Runner.java:)
public interface Runner<P extends Processor>
{
int runProcessors(Collection<P> processors);
}
(in some other file, in some method:)
Collection<?开发者_如何学Python extends Processor> processorsCollection = ...;
Runner<? extends Processor> runner = ...;
runner.runProcessors(processorsCollection);
IntelliJ marks the last line as an error:
"RunProcessors (java.util.Collection>) in Runner cannot be applied to (java.util.Collection>)".
I can't figure out whats wrong with what I did, especially since the error message is not quite clear..
any suggestions?
thanks.Both your collection and your runner allow for anything that extend processor. But, you can't guarantee they're the same.
Collection might be Collection<Processor1>
and Runner be Runner<Processor2>
.
Whatever method you have that in needs to be typed (I forget the exact syntax, but I'm sure you can find it!)
void <T extends Processor<T>> foo() {
Collection<T> procColl = ...
Runner<T> runner = ...
runner.runProc(procColl);
}
Edit:
@newAcct makes an excellent point: you need to genericize (is that a word?) your Processor. I've updated my code snippet above as to reflect this important change.
public interface Processor<P extends Processor>
{
Runner<P> getRunner();
}
public interface Runner<P extends Processor<P>>
{
int runProcessors(Collection<P> processors);
}
You have not made your situation clear and you're not showing us any of the code of the methods or of how you get the objects, so we don't really know what you're trying to do.
Your code is not type-safe. As @glowcoder mentioned, there is no way of knowing that the parameter of Collection
is the same as the parameter of Runner
. If you believe they are indeed the same, then that is based on code that you're not showing us (i.e. what happens in "...
"?)
You have written Processor
's getRunner()
method with a return type that has a wildcard parameter. This says when run it will return a Runner
with a mysterious parameter that it determines and we don't know. This doesn't make much sense and is probably not what you wanted.
Also depending on what you are doing, the runProcessors
method could possibly take a less strict bound. For example, perhaps <? extends P>
or even <? extends Processor>
if you don't need to modify the collection.
精彩评论