How to get collection type parameter (generics) from JvmTypeReference? [message #991013] |
Mon, 17 December 2012 02:03 |
Espinosa CZ Messages: 27 Registered: July 2009 |
Junior Member |
|
|
I am trying to write utility method to return collection type
@Inject TypeReferences typeReferences;
public JvmType getCollectionType(JvmTypeReference clazz) {
if (typeReferences.isInstanceOf(clazz, Collection.class)) {
collectionType = typeReferences.getArgument(clazz, 0);
return collectionType;
}
}
where clazz may represent java.util.List<String>, then I expect the method to return java.lang.String, or for java.util.Set<a.b.m.Book> to return a.b.m.Book.
The promisingly sounding typeReferences.getArgument(..) however returns "JvmParameterizedTypeReference: E" where getType() gives "JvmTypeParameter <E> java.util.List". Hmm. I got into blind alley.
Is it even possible or does the type erasure applies also for JvmTypeReference?
Thank you for any hints.
Espinosa
[Updated on: Mon, 17 December 2012 20:22] Report message to a moderator
|
|
|
|
|
|
Re: How to get collection type parameter (generics) from JvmTypeReference? [message #991312 is a reply to message #991254] |
Tue, 18 December 2012 13:30 |
Espinosa CZ Messages: 27 Registered: July 2009 |
Junior Member |
|
|
I have cracked it yesterday late night. Solved.
Sebastian, your question is very correct indeed.
The probed type was inferred from parent->field type.
Before anything JvmType related is to be set to Model AST, I have learned recently, one have to create an instance copy of the inferred JvmType. Otherwise all sorts of quirk behavior happen, like the Bug 396433.
I did not use the right copy creating library call:
public JvmTypeReference createDefensiveCopyOfJvmTypeReference(JvmTypeReference typeReference) {
return typeReferences.createTypeRef(typeReference.getType());
}
I have to use EcoreUtil.copy() or EcoreUtil.clone() instead.
public JvmTypeReference createDefensiveCopyOfJvmTypeReference(JvmTypeReference typeReference) {
return EcoreUtil.copy(typeReference);
}
Now it works as expected, type parameter (generics) is not lost and getCollectionType() works as expected, no change required:
@Inject TypeReferences typeReferences;
public JvmType getCollectionType(JvmTypeReference clazz) {
if (typeReferences.isInstanceOf(clazz, Collection.class)) {
collectionType = typeReferences.getArgument(clazz, 0);
return collectionType;
}
}
What is TypeReferences.createTypeRef(jvmType) supposed to do? It worked well until I started to play with parametrized types. You are supposed to provide type parameters yourself? Like createTypeRef(jvmType, jvmTypeParam1, .., jvmTypeParamN). If you do not, then the copy, the created type reference, exhibits "type erasure" like in Java. What is the point?
Regards
Espinosa
P.S.
https://bugs.eclipse.org/bugs/show_bug.cgi?id=396433
[Updated on: Tue, 18 December 2012 13:34] Report message to a moderator
|
|
|
Powered by
FUDForum. Page generated in 0.03800 seconds