The classes I am dealing with are as follows,
public interface One{
public Two get();
}
public class Foo{...}
public class Bar extends Foo{...}
public abstract class Parent<T extends Foo> implements One {...}
public abstract class Child<T extends Foo> extends Parent<T>
I have a static method that will return a Child object given a Foo object,
public static Child<? extends Foo> get(Foo f){...}
This metho开发者_高级运维d returns a child constructed from either a Foo or Bar object. The code that throws the error is this,
Foo f = new Foo();
Child<? extends Foo> child = O.get(f);
Two t = S.apply(child);
The apply method,
public Two apply(One o){...};
The error that gets thrown is,
apply(One) in S cannot be applied to (Child<capture#123 of ?>)
My current workaround for this problem is to change the code to this,
Foo f = new Foo();
Child<? extends Foo> child = O.get(f);
Object o = child;
One one = (One)o;
Two t = S.apply(one);
This resolves the error, I have no idea why the explicit cast to object needs to be there, but there it is.
Can anyone tell me if it is possible to modify the code so the casts are not necessary to get this to work?
I think I can tell you. Unfortunately, you are missing a lot of code, but I have seen this kind of thing before and know how to tackle it. Solving it involves a not often seen syntax of java.
Firstly, you have to type your static method, like this:
public static <T extends Foo> Child<T> get(Foo f){...}
Although not having seen the code, it is possible that given that change, that this will work:
Two t = S.apply(child);
However, if you need to, you can provide the type if you need to, like this:
Two t = S.<Two>apply(child); // Cool huh?
This syntax is how you coerce the type for a typed static method.
I'm not sure if this exact code will work for you, because you haven't provided enough code, but the solution will be pretty close to this if not this.
If this doesn't work, post all of the relevant code you have and I'll try to make it work for you.
精彩评论