MethodInvocation -- get calling Type? [message #250298] |
Wed, 19 December 2007 15:35  |
Eclipse User |
|
|
|
Hi,
if I have an expression like
a.methodA();
is there any way of getting the "a" from a MethodInvocation AST node (or
in fact: from _any_ AST node)? I'd like to know which type calls the
method...
For example, consider this:
package A;
public class A {
public methodA() {}
}
package B;
public class B extends A {
public methodB() {
A a = new A();
a.methodA();
}
}
Now, I would like to check, if "methodA" could also be declared as
protected (which obviously it cannot). It could be declared as
"protected", iff methodB would call it _directly_ without first creating
an instance of A (because B is a subclass of A). So: Can I somehow
determine if B calls methodA directly or uses a new instance of class A?
I hope I explained myself ok, if not, please ask for me to clarify and
I'll do my best!
Thanks for any help that you could provide.
Philipp
|
|
|
Re: MethodInvocation -- get calling Type? [message #250319 is a reply to message #250298] |
Thu, 20 December 2007 08:06  |
Eclipse User |
|
|
|
After some experimenting (and using the ASTView plug-in), I could solve
the problem:
Given an MethodInvocation node in an AST where bindings are resolved, you
can get the calling type of the method by using:
<node is the MethodInvocation node>
Expression exp = node.getExpression();
ITypeBinding invocationType = null;
IMember declaringMember = null;
if (exp instanceof SimpleName) {
SimpleName name = (SimpleName) exp;
IBinding binding = name.resolveBinding();
if (binding != null && binding instanceof IVariableBinding) {
IVariableBinding varBinding = (IVariableBinding) binding;
invocationType = varBinding.getType();
if (varBinding.getDeclaringClass() != null) {
declaringMember = (IMember) varBinding.
getDeclaringClass().getJavaElement();
}
if (declaringMember == null) {
if (varBinding.getDeclaringMethod() != null) {
if (varBinding.getDeclaringMethod().getDeclaringClass() != null) {
declaringMember = (IMember)
varBinding.getDeclaringMethod().
getDeclaringClass().getJavaElement();
}
}
}
}
}
Now, you have the type of the class that invokes the method in
invocationType and the type of the class where the invocation takes place
in declaringMember.
Note that declaringMember might be an IMethod object or an IType object --
it depends where the method has been invoked.
Have fun with it,
Philipp
|
|
|
Powered by
FUDForum. Page generated in 0.02790 seconds