I'm working on a Java 7 based project. I wanted to introduce a generic parameter on one of the classes, so that I can slowly eliminate the class casts required to make the code work.
Let's introduce a class, that is similar to the one I'm working on:
public class A {
public List<B> getB() { ... }
}
B
has lots of child classes, which when used, need to be casted, which is not ideal obviously. The modification I'd like to make is like this:
public class A<T extends B> {
public List<T> getB() {...}
}
This can eliminate the casting required in some cases. However, A
is used in a big part of the project, which makes it not too efficient to go through and rewrite every case it's used.
I hoped, that using the raw A
class will make it so that getB()
will return a type of B
. The reality is that if used raw, getB()
will return a type of Object
instead. Is it some Java 7 related behavior, or am I overlooking something? Is there a way to make getB()
return a type of B
when A
is raw? I didn't seem to come across this issue in Java 8, though I haven't really worked on a project this poorly structured either.
Edit: In the comments, I was requested for concrete code example, where the issue occurs. Assuming the above classes (edited slightly to better fit my actual scenario):
A a = new A();
for(B b: a.getB()) { // Compiler error, because `getB()` returns a list of `Object`s instead of `B`s.
...
}
A<B> a = new A<B>();
for(B b: a.getB()) { // Everything is fine here obviously
...
}