My problem can be summed-up by this snippet:
public interface TheClass<T> {
public void theMethod(T obj);
}
public class A {
private TheClass<?> instance;
public A(TheClass<?> instance) {
this.instance = instance;
}
public void doWork(Object target) {
instance.theMethod(target); // Won't compile!
// However, I know that the target can be passed to the
// method safely because its type matches.
}
}
My class A
uses an instance of TheClass
with its generics type unknown. It features a method with a target passed as Object
since the TheClass
instance can be parameterized with any class. However, the compiler won't allow me to pass the target like this, which is normal.
What should I do to circumvent this issue?
A dirty solution is to declare the instance as TheClass<? super Object>
, which works fine but is semantically wrong...
Another solution I used before was to declare the instance as raw type, just TheClass
, but it's bad practice, so I want to correct my mistake.
Solution
public class A {
private TheClass<Object> instance; // type enforced here
public A(TheClass<?> instance) {
this.instance = (TheClass<Object>) instance; // cast works fine
}
public void doWork(Object target) {
instance.theMethod(target);
}
}
public class A {
private TheClass<Object> instance;
public A(TheClass<Object> instance) {
this.instance = instance;
}
public void do(Object target) {
instance.theMethod(target);
}
}
or
public class A<T> {
private TheClass<T> instance;
public A(TheClass<T> instance) {
this.instance = instance;
}
public void do(T target) {
instance.theMethod(target);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With