Reputation: 19854
The build method below creates an instance of TypedMemberDTO
.
TypedMemberDTO
can contain a typed List
The Member.getDetails
returns an Object
type, which I know will only be one of 2 types at runtime. These types have nothing in common apart from extending Object
.
What I want to do is create a build method that uses generics to set the details in the TypedMemberDTO
.
The code compiles fine, and runs fine, although I'm a bit confused as to what the <U>
typing actually provides me.
In reality, if I used raw types here instead of <U>
, would I have achieved the same compile time benefits?
Is there a better way to write the build method?
public class TypedMemberDTO<T> extends MemberDTO {
private List<T> details;
public List<T> getDetails() {
return details;
}
public void setDetails(List<T> details) {
this.details = details;
}
}
public <U> TypedMemberDTO<?> build(Member member, String attributeName) {
TypedMemberDTO<U> typedMemberDTO = new TypedMemberDTO<U>();
List<U> dtos = (List<U>) member.getDetails(attributeName);
typedMemberDTO.setDetails(dtos);
return typedMemberDTO;
}
Upvotes: 0
Views: 43
Reputation: 34628
Generics don't exist at runtime. They are only used at compile time to allow your code to avoid as many ClassCastException
s at runtime as possible by avoiding coerced casts. But at runtime, the type of objects belonging to generic classes is simply the raw type.
This means that if your Member
class is not generic, as the compiler cannot tell what kind of List
it has returned, there is no difference between using this and using raw types.
Generic methods are there to impose particular constraints on the relationship between parameter types and return type or between the type of one parameter and another. In this case, you do not have any mention of the generic type U in the parameter list. So in essence, it checks nothing.
Upvotes: 1