下面列出了org.eclipse.jdt.core.dom.MethodDeclaration#parameters ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean visit(MethodDeclaration node) {
int start = _unit.getLineNumber(node.getStartPosition());
int end = _unit.getLineNumber(node.getStartPosition() + node.getLength());
if(start <= _line && _line <= end){
for(Object object : node.parameters()){
SingleVariableDeclaration svd = (SingleVariableDeclaration) object;
_vars.put(svd.getName().toString(), svd.getType());
}
if(node.getBody() != null){
MethodVisitor methodVisitor = new MethodVisitor();
node.getBody().accept(methodVisitor);
methodVisitor.dumpVarMap();
}
return false;
}
return true;
}
/**
* @param node
* @return
*/
public static String getMethodType(final MethodDeclaration node) {
final StringBuffer typeSb = new StringBuffer();
if (node.getReturnType2() != null) {
typeSb.append(node.getReturnType2().toString()).append("(");
} else if (node.isConstructor()) {
typeSb.append("constructor(");
} else {
typeSb.append("void(");
}
for (final Object svd : node.parameters()) {
final SingleVariableDeclaration decl = (SingleVariableDeclaration) svd;
typeSb.append(decl.getType().toString());
typeSb.append(",");
}
typeSb.append(")");
final String methodType = typeSb.toString();
return methodType;
}
@SuppressWarnings("unchecked")
private void addAsyncParameters(AST ast, MethodDeclaration asyncMethodDecl) {
List<SingleVariableDeclaration> asyncMethodParams = asyncMethodDecl.parameters();
// Clone all the existing sync method parameters
asyncMethodParams.addAll(JavaASTUtils.cloneParameters(ast,
getSyncMethodDeclaration().parameters(), getImportRewrite()));
List<String> existingParamNames = new ArrayList<String>();
for (SingleVariableDeclaration param : asyncMethodParams) {
existingParamNames.add(param.getName().getIdentifier());
}
String callbackParameterName = StringUtilities.computeUniqueName(
existingParamNames.toArray(new String[0]), "callback");
// Add the AsyncCallback parameter to the end
asyncMethodParams.add(Util.createAsyncCallbackParameter(ast,
getSyncMethodDeclaration().getReturnType2(), callbackParameterName,
getImportRewrite()));
}
ParameterAnnotationRewriteOperation(CompilationUnit unit, MethodDeclaration method, String annotationToAdd, String annotationToRemove, String paramName, boolean allowRemove, String message) {
fUnit= unit;
fKey= method.resolveBinding().getKey();
fAnnotationToAdd= annotationToAdd;
fAnnotationToRemove= annotationToRemove;
fAllowRemove= allowRemove;
fMessage= message;
for (Object param : method.parameters()) {
SingleVariableDeclaration argument= (SingleVariableDeclaration) param;
if (argument.getName().getIdentifier().equals(paramName)) {
fArgument= argument;
fKey+= argument.getName().getIdentifier();
return;
}
}
// shouldn't happen, we've checked that paramName indeed denotes a parameter.
throw new RuntimeException("Argument " + paramName + " not found in method " + method.getName().getIdentifier()); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Returning method full name. [access modifier + return + name + (parameters list)]
* @param methodVersion
* @return
*/
private String getFullNameMethod(MethodDeclaration methodVersion){
String nameMethod = "";
if(methodVersion != null){
String modifiersMethod = (methodVersion.modifiers() != null) ? (StringUtils.join(methodVersion.modifiers(), " ") + " ") : " ";
String returnMethod = (methodVersion.getReturnType2() != null) ? (methodVersion.getReturnType2().toString() + " ") : "";
String parametersMethod = (methodVersion.parameters() != null) ? StringUtils.join(methodVersion.parameters(), ", ") : " ";
nameMethod = modifiersMethod + returnMethod + methodVersion.getName() + "(" + parametersMethod + ")";
}
return nameMethod;
}
/**
* Returning method name. Example: [name(parameters list)]
* @param methodVersion
* @return
*/
private String getSimpleNameMethod(MethodDeclaration methodVersion){
String nameMethod = "";
if(methodVersion != null){
String parametersMethod = (methodVersion.parameters() != null) ? StringUtils.join(methodVersion.parameters(), ", ") : " ";
nameMethod = methodVersion.getName() + "(" + parametersMethod + ")";
}
return nameMethod;
}
public static Pair<String, String> getTypeDecAndMethodDec(ASTNode node) {
ASTNode parent = node.getParent();
String methodName = null;
String className = null;
while(parent != null){
if(parent instanceof MethodDeclaration){
MethodDeclaration methodDeclaration = (MethodDeclaration) parent;
methodName = methodDeclaration.getName().getFullyQualifiedName();
String params = "";
for(Object obj : methodDeclaration.parameters()){
SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) obj;
params += ","+singleVariableDeclaration.getType().toString();
}
methodName += params;
} else if(parent instanceof TypeDeclaration){
TypeDeclaration typeDeclaration = (TypeDeclaration) parent;
if(Modifier.isPublic(typeDeclaration.getModifiers()) && className != null){
className = typeDeclaration.getName().getFullyQualifiedName() + "$" + className;
} else {
if(className == null) {
className = ((TypeDeclaration)parent).getName().getFullyQualifiedName();
}
}
} else if(parent instanceof EnumDeclaration){
className = ((EnumDeclaration)parent).getName().getFullyQualifiedName();
}
parent = parent.getParent();
}
return new Pair<String, String>(className, methodName);
}
/**
* Returns the callback parameter declaration from an async method.
*
* @param method async method declaration
* @return callback parameter declaration
*/
public static SingleVariableDeclaration getCallbackParameter(
MethodDeclaration method) {
@SuppressWarnings("unchecked")
List<SingleVariableDeclaration> asyncParameters = method.parameters();
if (asyncParameters.isEmpty()) {
return null;
}
// Grab the last parameter type, which should be the callback
SingleVariableDeclaration callback = asyncParameters.get(asyncParameters.size() - 1);
ITypeBinding callbackBinding = callback.getType().resolveBinding();
if (callbackBinding == null) {
return null;
}
// Make sure the callback is of type AsyncCallback
String callbackBaseTypeName = callbackBinding.getErasure().getQualifiedName();
if (RemoteServiceUtilities.ASYNCCALLBACK_QUALIFIED_NAME.equals(callbackBaseTypeName)) {
return callback;
}
return null;
}
private List<ConstructorParameterSetterBuilderField> extractArguments(MethodDeclaration constructor) {
List<ConstructorParameterSetterBuilderField> result = new ArrayList<>();
List<SingleVariableDeclaration> parameters = constructor.parameters();
for (int i = 0; i < parameters.size(); ++i) {
result.add(createConstructorParameterSetterBuilderField(parameters.get(i), i));
}
return result;
}
private static boolean getAssignAllParamsToFieldsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
node = ASTNodes.getNormalizedNode(node);
ASTNode parent = node.getParent();
if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
return false;
}
MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
if (methodDecl.getBody() == null) {
return false;
}
List<SingleVariableDeclaration> parameters = methodDecl.parameters();
if (parameters.size() <= 1) {
return false;
}
ITypeBinding parentType = Bindings.getBindingOfParentType(node);
if (parentType == null || parentType.isInterface()) {
return false;
}
for (SingleVariableDeclaration param : parameters) {
IVariableBinding binding = param.resolveBinding();
if (binding == null || binding.getType() == null) {
return false;
}
}
if (resultingCollections == null) {
return true;
}
AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), parameters, IProposalRelevance.ASSIGN_ALL_PARAMS_TO_NEW_FIELDS);
resultingCollections.add(fieldProposal);
return true;
}
private void addLinkedRanges(ASTRewrite rewrite, MethodDeclaration newStub) {
List<SingleVariableDeclaration> parameters= newStub.parameters();
for (int i= 0; i < parameters.size(); i++) {
SingleVariableDeclaration curr= parameters.get(i);
String name= curr.getName().getIdentifier();
addLinkedPosition(rewrite.track(curr.getType()), false, "arg_type_" + name); //$NON-NLS-1$
addLinkedPosition(rewrite.track(curr.getName()), false, "arg_name_" + name); //$NON-NLS-1$
}
}
public static SimpleName isSetter(MethodDeclaration methodDeclaration) {
Block methodBody = methodDeclaration.getBody();
List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
if(methodBody != null) {
List<Statement> statements = methodBody.statements();
if(statements.size() == 1 && parameters.size() == 1) {
Statement statement = statements.get(0);
if(statement instanceof ExpressionStatement) {
ExpressionStatement expressionStatement = (ExpressionStatement)statement;
Expression expressionStatementExpression = expressionStatement.getExpression();
if(expressionStatementExpression instanceof Assignment) {
Assignment assignment = (Assignment)expressionStatementExpression;
Expression rightHandSide = assignment.getRightHandSide();
if(rightHandSide instanceof SimpleName) {
SimpleName rightHandSideSimpleName = (SimpleName)rightHandSide;
if(rightHandSideSimpleName.resolveBinding().isEqualTo(parameters.get(0).resolveBinding())) {
Expression leftHandSide = assignment.getLeftHandSide();
if(leftHandSide instanceof SimpleName) {
return (SimpleName)leftHandSide;
}
else if(leftHandSide instanceof FieldAccess) {
FieldAccess fieldAccess = (FieldAccess)leftHandSide;
return fieldAccess.getName();
}
}
}
}
}
}
}
return null;
}
private void addLinkedRanges(ASTRewrite rewrite, MethodDeclaration newStub) {
List<SingleVariableDeclaration> parameters= newStub.parameters();
for (int i= 0; i < parameters.size(); i++) {
SingleVariableDeclaration curr= parameters.get(i);
String name= curr.getName().getIdentifier();
addLinkedPosition(rewrite.track(curr.getType()), false, "arg_type_" + name); //$NON-NLS-1$
addLinkedPosition(rewrite.track(curr.getName()), false, "arg_name_" + name); //$NON-NLS-1$
}
}
@Override
@SuppressWarnings("unchecked")
protected List<SingleVariableDeclaration> adjustSrcParams(
MethodDeclaration method) {
// The source method is in the sync interface
return method.parameters();
}
@Override
@SuppressWarnings("unchecked")
protected List<SingleVariableDeclaration> adjustSrcParams(
MethodDeclaration method) {
// The source method is in the async interface
List<SingleVariableDeclaration> params = method.parameters();
if (Util.getCallbackParameter(method) != null) {
params = params.subList(0, params.size() - 1);
}
return params;
}
/**
* {@inheritDoc}
*/
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
ImportRemover importRemover= cuRewrite.getImportRemover();
AST ast= rewrite.getAST();
HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
for (int i= 0; i < fExpressions.size(); i++) {
ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);
AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();
Object object= bodyDeclarations.get(0);
if (!(object instanceof MethodDeclaration))
continue;
MethodDeclaration methodDeclaration= (MethodDeclaration) object;
HashSet<String> excludedNames= new HashSet<String>();
if (i != 0) {
for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
excludedNames.addAll(cicToNewNames.get(convertedCic));
}
}
}
HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();
// use short form with inferred parameter types and without parentheses if possible
LambdaExpression lambdaExpression= ast.newLambdaExpression();
List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
lambdaExpression.setParentheses(methodParameters.size() != 1);
for (SingleVariableDeclaration methodParameter : methodParameters) {
VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
lambdaParameters.add(lambdaParameter);
}
Block body= methodDeclaration.getBody();
List<Statement> statements= body.statements();
ASTNode lambdaBody= body;
if (statements.size() == 1) {
// use short form with just an expression body if possible
Statement statement= statements.get(0);
if (statement instanceof ExpressionStatement) {
lambdaBody= ((ExpressionStatement) statement).getExpression();
} else if (statement instanceof ReturnStatement) {
Expression returnExpression= ((ReturnStatement) statement).getExpression();
if (returnExpression != null) {
lambdaBody= returnExpression;
}
}
}
//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
// lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
Expression replacement= lambdaExpression;
if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
CastExpression cast= ast.newCastExpression();
cast.setExpression(lambdaExpression);
ImportRewrite importRewrite= cuRewrite.getImportRewrite();
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
cast.setType(castType);
importRemover.registerAddedImports(castType);
replacement= cast;
}
rewrite.replace(classInstanceCreation, replacement, group);
importRemover.registerRemovedNode(classInstanceCreation);
importRemover.registerRetainedNode(lambdaBody);
}
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
String name= fTypeNode.getName().getIdentifier();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(true);
decl.setName(ast.newSimpleName(name));
Block body= ast.newBlock();
decl.setBody(body);
SuperConstructorInvocation invocation= null;
List<SingleVariableDeclaration> parameters= decl.parameters();
String[] paramNames= getArgumentNames(binding);
ITypeBinding enclosingInstance= getEnclosingInstance();
if (enclosingInstance != null) {
invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
}
if (binding == null) {
decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
} else {
decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));
ITypeBinding[] params= binding.getParameterTypes();
for (int i= 0; i < params.length; i++) {
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List<Type> thrownExceptions= decl.thrownExceptionTypes();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext, TypeLocation.EXCEPTION);
thrownExceptions.add(excType);
}
if (invocation == null) {
invocation= ast.newSuperConstructorInvocation();
}
List<Expression> arguments= invocation.arguments();
for (int i= 0; i < paramNames.length; i++) {
Name argument= ast.newSimpleName(paramNames[i]);
arguments.add(argument);
addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
}
}
String bodyStatement = (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
public void visit(MethodDeclaration node) {
qty = node.parameters() == null ? 0 : node.parameters().size();
}
private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding binding, ASTRewrite rewrite, ImportRewriteContext importRewriteContext, CodeGenerationSettings commentSettings) throws CoreException {
String name= fTypeNode.getName().getIdentifier();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(true);
decl.setName(ast.newSimpleName(name));
Block body= ast.newBlock();
decl.setBody(body);
SuperConstructorInvocation invocation= null;
List<SingleVariableDeclaration> parameters= decl.parameters();
String[] paramNames= getArgumentNames(binding);
ITypeBinding enclosingInstance= getEnclosingInstance();
if (enclosingInstance != null) {
invocation= addEnclosingInstanceAccess(rewrite, importRewriteContext, parameters, paramNames, enclosingInstance);
}
if (binding == null) {
decl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
} else {
decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, binding.getModifiers()));
ITypeBinding[] params= binding.getParameterTypes();
for (int i= 0; i < params.length; i++) {
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(getImportRewrite().addImport(params[i], ast, importRewriteContext));
var.setName(ast.newSimpleName(paramNames[i]));
parameters.add(var);
}
List<Type> thrownExceptions= decl.thrownExceptionTypes();
ITypeBinding[] excTypes= binding.getExceptionTypes();
for (int i= 0; i < excTypes.length; i++) {
Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext);
thrownExceptions.add(excType);
}
if (invocation == null) {
invocation= ast.newSuperConstructorInvocation();
}
List<Expression> arguments= invocation.arguments();
for (int i= 0; i < paramNames.length; i++) {
Name argument= ast.newSimpleName(paramNames[i]);
arguments.add(argument);
addLinkedPosition(rewrite.track(argument), false, "arg_name_" + paramNames[i]); //$NON-NLS-1$
}
}
String bodyStatement= (invocation == null) ? "" : ASTNodes.asFormattedString(invocation, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true)); //$NON-NLS-1$
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), name, name, true, bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
if (commentSettings != null) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), name, decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private ITypeBinding[] resolveBindings(String[] types, RefactoringStatus[] results, boolean firstPass) throws CoreException {
//TODO: split types into parameterTypes and returnType
int parameterCount= types.length - 1;
ITypeBinding[] typeBindings= new ITypeBinding[types.length];
StringBuffer cuString= new StringBuffer();
cuString.append(fStubTypeContext.getBeforeString());
int offsetBeforeMethodName= appendMethodDeclaration(cuString, types, parameterCount);
cuString.append(fStubTypeContext.getAfterString());
// need a working copy to tell the parser where to resolve (package visible) types
ICompilationUnit wc= fMethod.getCompilationUnit().getWorkingCopy(new WorkingCopyOwner() {/*subclass*/}, new NullProgressMonitor());
try {
wc.getBuffer().setContents(cuString.toString());
CompilationUnit compilationUnit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(wc, true);
ASTNode method= NodeFinder.perform(compilationUnit, offsetBeforeMethodName, METHOD_NAME.length()).getParent();
Type[] typeNodes= new Type[types.length];
if (method instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) method;
typeNodes[parameterCount]= methodDeclaration.getReturnType2();
List<SingleVariableDeclaration> parameters= methodDeclaration.parameters();
for (int i= 0; i < parameterCount; i++)
typeNodes[i]= parameters.get(i).getType();
} else if (method instanceof AnnotationTypeMemberDeclaration) {
typeNodes[0]= ((AnnotationTypeMemberDeclaration) method).getType();
}
for (int i= 0; i < types.length; i++) {
Type type= typeNodes[i];
if (type == null) {
String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_couldNotResolveType, BasicElementLabels.getJavaElementName(types[i]));
results[i]= RefactoringStatus.createErrorStatus(msg);
continue;
}
results[i]= new RefactoringStatus();
IProblem[] problems= ASTNodes.getProblems(type, ASTNodes.NODE_ONLY, ASTNodes.PROBLEMS);
if (problems.length > 0) {
for (int p= 0; p < problems.length; p++)
if (isError(problems[p], type))
results[i].addError(problems[p].getMessage());
}
ITypeBinding binding= handleBug84585(type.resolveBinding());
if (firstPass && (binding == null || binding.isRecovered())) {
types[i]= qualifyTypes(type, results[i]);
}
typeBindings[i]= binding;
}
return typeBindings;
} finally {
wc.discardWorkingCopy();
}
}