I can access all methods ITypeusing the method getMethods(). Is there an effective way to determine if such an IMethodaccessor or mutator (getter / setter)?
Checking that the name IMethodmatches the schema prefix + NameOfAttributewith the help prefix ∈ {"get", "set", "is"}will help me find the obvious ones, but if the accessor or mutator (getter / setter) is not named that way, this will not work.
Is there a better way?
EDIT . I only want to define getter / setter methods that directly get / set the attribute ITypeand do nothing.
EDIT2 : Used technical terms: accessor and mutator
EDIT3 : here is my solution after reading all the answers:
private boolean isAccessor(IMethod method) throws JavaModelException {
if (isAccessMethod("get", method) || isAccessMethod("is", method)) {
return method.getNumberOfParameters() == 0 && !Signature.SIG_VOID.equals(method.getReturnType());
}
return false;
}
private boolean isMutator(IMethod method) throws JavaModelException {
if (isAccessMethod("set", method)) {
return method.getNumberOfParameters() == 1 && Signature.SIG_VOID.equals(method.getReturnType());
}
return false;
}
private boolean isAccessMethod(String prefix, IMethod method) throws JavaModelException {
IType type = method.getDeclaringType();
for (IField field : type.getFields()) {
if (method.getElementName().equalsIgnoreCase(prefix + field.getElementName())) {
return true;
}
}
return false;
}
IMPORTANT: This solution meets my requirements, but ignores some important cases (see accepted answer ) . This still does not test the functionality of the method, but it works very well. It checks the method name for the scheme I proposed. But it also checks the number of parameters and return type voidor not. If someone wanted to improve this, he could also check to see if the return / parameter type of the getter matched the type of the field that matches the method name.
source
share