Reputation: 21
I am using the BCEL
library to analyze some code. I came across a method (getAllNames())
whose return type is List< Name >
. I want to be able to obtain the return type of this method.
I want to be able to obtain the full class of "Name".
I have tried using the < Instruction.getReturnType() >
method in my method visitor class but for this specific method I get the result "java.util.List". I want the generic type "com.instant.Name" instead.
The signature for the method is like so:
public List<Name> getAllNames() {
...
}
I also have a org.apache.bcel.generic.MethodGen object that I create before visiting the method using org.apache.bcel.classfile.Method
When I try to get return type it again gives "java.util.List"
I expect the output of MethodGen.getReturnType() to be "com.instant.Name" but the actual output is "java.util.List"
Upvotes: -1
Views: 524
Reputation: 13225
Contrary to some comments the information is obviously there, type erasure does not happen on the interface level - just as Eclipse/NetBeans/IntelliJ/etc. can get the exact type/return type of class members, you can do that too:
public class Name {
public List<Name> getAllNames(){return null;}
public static void main(String[] args) throws Exception {
Method m=Name.class.getMethod("getAllNames");
ParameterizedType pt=(ParameterizedType)m.getGenericReturnType();
System.out.println(pt.getActualTypeArguments()[0]);
}
}
BCEL
is another story, I am not familiar with it, however the very end of FieldOrMethod.java
, there is a method called getGenericSignature()
. You may find it useful already (though presumably it produces a signature), or you can replicate the loop inside, over the attributes
(you can get them via getAttributes()
), checking for an occurrence of instanceof Signature
:
Attribute a[]=m.getAttributes(); // where is the org.apache.bcel.classfile.Method you have
for(int i=0;i<a.length;i++)
if(a[i] instanceof Signature)
System.out.println(a[i]); // this is just a test of course.
The real code suggests that there can be only one such attribute and the loop could exit afterwards, but it made me think about types having multiple parameters, like Map
-s...
getGenericSignature()
itself does not occur anywhere else (neither tested, nor used), so I can only hope that it (and consequently, the approach described above) really works.
Upvotes: 0