Resolve generic type in subclass? [message #876443] |
Thu, 24 May 2012 11:52  |
Eclipse User |
|
|
|
Here is a scenario:
public class Super<T> {
protected T id;
}
public class Sub extends Super<Long> {}
Is there a way to evaluate the type of the field "id" within the scope of the class "Sub" using available API? I'm currently using JDT dom API, but other public API is acceptable.
|
|
|
Re: Resolve generic type in subclass? [message #877438 is a reply to message #876443] |
Sat, 26 May 2012 14:25   |
Eclipse User |
|
|
|
The pure dom AST doesn't have the information about type substitutions, but if you request the binding (TypeDeclaration#resolveBinding()) you'll enter the land of resolved type information.
Here's a passing unit test:
public void testResolvedField() throws JavaModelException {
this.workingCopy = getWorkingCopy("/Converter15/src/X.java", true/*resolve*/);
String contents =
"public class X<T> {\n" +
" T f;\n" +
"}\n" +
"class Sub extends X<String> {}\n" +
"class Sub2 extends X<Number> {}\n";
ASTNode node = buildAST(
contents,
this.workingCopy,
false);
assertEquals("Not a compilation unit", ASTNode.COMPILATION_UNIT, node.getNodeType());
CompilationUnit unit = (CompilationUnit) node;
assertProblemsSize(unit, 0);
TypeDeclaration type = (TypeDeclaration) unit.types().get(1);
ITypeBinding typeBinding = type.resolveBinding();
ITypeBinding superType = typeBinding.getSuperclass();
IVariableBinding[] fields = superType.getDeclaredFields();
assertEquals(fields[0].getType().getName(), "String");
type = (TypeDeclaration) unit.types().get(2);
typeBinding = type.resolveBinding();
superType = typeBinding.getSuperclass();
fields = superType.getDeclaredFields();
assertEquals(fields[0].getType().getName(), "Number");
}
HTH,
Stephan
[Updated on: Sat, 26 May 2012 14:25] by Moderator
|
|
|
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.03737 seconds