下面列出了org.eclipse.jdt.core.dom.MethodDeclaration#getReturnType2 ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @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;
}
/**
* Creates the corresponding statement for the method invocation, based on
* the return type.
*
* @param declaration the method declaration where the invocation statement
* is inserted
* @param invocation the method invocation being encapsulated by the
* resulting statement
* @return the corresponding statement
*/
protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) {
Assert.isNotNull(declaration);
Assert.isNotNull(invocation);
Statement statement= null;
final Type type= declaration.getReturnType2();
if (type == null) {
statement= createExpressionStatement(invocation);
} else {
if (type instanceof PrimitiveType) {
final PrimitiveType primitive= (PrimitiveType) type;
if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
statement= createExpressionStatement(invocation);
} else {
statement= createReturnStatement(invocation);
}
} else {
statement= createReturnStatement(invocation);
}
}
return statement;
}
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof ReturnStatement)) {
return;
}
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
Expression expression= returnStatement.getExpression();
if (expression == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methDecl= (MethodDeclaration) decl;
Type retType= methDecl.getReturnType2();
if (retType == null || retType.resolveBinding() == null) {
return;
}
TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
}
}
/**
* @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;
}
/**
* Creates the corresponding statement for the method invocation, based on
* the return type.
*
* @param declaration the method declaration where the invocation statement
* is inserted
* @param invocation the method invocation being encapsulated by the
* resulting statement
* @return the corresponding statement
*/
protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) {
Assert.isNotNull(declaration);
Assert.isNotNull(invocation);
Statement statement= null;
final Type type= declaration.getReturnType2();
if (type == null)
statement= createExpressionStatement(invocation);
else {
if (type instanceof PrimitiveType) {
final PrimitiveType primitive= (PrimitiveType) type;
if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID))
statement= createExpressionStatement(invocation);
else
statement= createReturnStatement(invocation);
} else
statement= createReturnStatement(invocation);
}
return statement;
}
@Override
public boolean visit(MethodDeclaration node) {
if (!node.isConstructor()) {
if (node.getReturnType2() != null
&& !Utils.isAllowedParameterType(node.getReturnType2().resolveBinding(), true)) {
collector.report(INVALID_PARAMETER_TYPE.create(collector.getSourceInfo(), node.getReturnType2()));
}
}
Utils.checkModifiers(collector, node);
for (Object obj : node.parameters()) {
SingleVariableDeclaration param = (SingleVariableDeclaration) obj;
if (!Utils.isAllowedParameterType(param.getType().resolveBinding(), false)) {
collector.report(INVALID_PARAMETER_TYPE.create(collector.getSourceInfo(), param.getType()));
}
}
// TODO: check body
return false;
}
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
if (methodDeclaration == null)
return new HashSet<ITypeBinding>(0);
Set<ITypeBinding> result= new HashSet<ITypeBinding>();
ITypeBinding binding= null;
Type returnType= methodDeclaration.getReturnType2();
if (returnType != null) {
binding = returnType.resolveBinding();
if (binding != null)
result.add(binding);
}
for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
binding = iter.next().getType().resolveBinding();
if (binding != null)
result.add(binding);
}
for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
binding= iter.next().resolveBinding();
if (binding != null)
result.add(binding);
}
return result;
}
public static Boolean isDiffByReturn(MethodDeclaration methodVersion1, MethodDeclaration methodVersion2){
Type returnType1 = methodVersion1.getReturnType2();
Type returnType2 = methodVersion2.getReturnType2();
if(returnType1 != null && returnType2 != null && !returnType1.toString().equals(returnType2.toString())){
return true;
}
return false;
}
/**
* 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;
}
public static String buildMethodInfoString(MethodDeclaration node) {
String currentClassName = getFullClazzName(node);
if (currentClassName == null) {
return null;
}
StringBuffer buffer = new StringBuffer(currentClassName + "#");
String retType = "?";
if (node.getReturnType2() != null) {
retType = node.getReturnType2().toString();
}
StringBuffer param = new StringBuffer("?");
for (Object object : node.parameters()) {
if (!(object instanceof SingleVariableDeclaration)) {
param.append(",?");
} else {
SingleVariableDeclaration singleVariableDeclaration = (SingleVariableDeclaration) object;
param.append("," + singleVariableDeclaration.getType().toString());
}
}
// add method return type
buffer.append(retType + "#");
// add method name
buffer.append(node.getName().getFullyQualifiedName() + "#");
// add method params, NOTE: the first parameter starts at index 1.
buffer.append(param);
return buffer.toString();
}
public static Set<ITypeBinding> getTypesUsedInDeclaration(MethodDeclaration methodDeclaration) {
if (methodDeclaration == null) {
return new HashSet<>(0);
}
Set<ITypeBinding> result= new HashSet<>();
ITypeBinding binding= null;
Type returnType= methodDeclaration.getReturnType2();
if (returnType != null) {
binding = returnType.resolveBinding();
if (binding != null) {
result.add(binding);
}
}
for (Iterator<SingleVariableDeclaration> iter= methodDeclaration.parameters().iterator(); iter.hasNext();) {
binding = iter.next().getType().resolveBinding();
if (binding != null) {
result.add(binding);
}
}
for (Iterator<Type> iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) {
binding= iter.next().resolveBinding();
if (binding != null) {
result.add(binding);
}
}
return result;
}
private MethodDecl getMethodDecl(MethodDeclaration node) {
String qualifiedTypeName = currentPackage + "."
+ Joiner.on(".").skipNulls().join(typesInFile);
SimpleName nameNode = node.getName();
String methodName = nameNode.toString();
String returnType = "";
if (node.getReturnType2() != null) {
returnType = getNameOfType(node.getReturnType2());
}
Map<String, String> params = new HashMap<>();
for (Object p : node.parameters()) {
if (p instanceof SingleVariableDeclaration) {
SingleVariableDeclaration svd = (SingleVariableDeclaration) p;
String varName = svd.getName().toString();
Type type = svd.getType();
String typeName = getNameOfType(type);
params.put(varName, typeName);
} else {
System.err.println("Unxepected AST node type for param - " + p);
}
}
return new MethodDecl(methodName, qualifiedTypeName, returnType, nameNode
.getStartPosition(), params);
}
@Override
public boolean visit(final MethodDeclaration node) {
final String name = node.getName().toString();
final Type returnType = node.getReturnType2();
methodReturnTypes.put(currentPackage + scopeName + "." + name, returnType);
return super.visit(node);
}
@Override
public boolean visit(MethodDeclaration node) {
org.eclipse.jdt.core.dom.Type type = node.getReturnType2();
if (!(type instanceof org.eclipse.jdt.core.dom.PrimitiveType && ((org.eclipse.jdt.core.dom.PrimitiveType) type).getPrimitiveTypeCode().toString().equals("void"))) {
methods++;
methods2++;
}
return true;
}
@Override
public boolean visit(MethodDeclaration node) {
org.eclipse.jdt.core.dom.Type type = node.getReturnType2();
if (type instanceof org.eclipse.jdt.core.dom.PrimitiveType && ((org.eclipse.jdt.core.dom.PrimitiveType) type).getPrimitiveTypeCode().toString().equals("void")) {
methods++;
methods2++;
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean visit(MethodDeclaration node) {
AbstractMethod method = new AbstractMethod();
method.setConstructor(node.isConstructor());
method.setVarargs(node.isVarargs());
StringBuilder builder = null;
builder = new StringBuilder();
builder.append(node.getName().getIdentifier()).append("(");
List<AbstractParameter> params = new ArrayList<>();
for (SingleVariableDeclaration var : (List<SingleVariableDeclaration>) node.parameters()) {
IVariableBinding varBind = var.resolveBinding();
AbstractParameter param = new AbstractParameter(varBind.getType().getQualifiedName(), varBind.getName());
params.add(param);
builder.append(param.getType() + ",");
}
if (builder.substring(builder.length() - 1).equals(",")) {
builder.replace(builder.length() - 1, builder.length(), ")");
} else {
builder.append(")");
}
method.setName(builder.toString());
method.setParameters(params);
verifyAccessorMethod(method);
List<String> throwsList = new ArrayList<String>();
List<Type> types = node.thrownExceptionTypes();
for (Type type : types) {
throwsList.add(type.toString());
}
method.setThrownsExceptions(throwsList);
List<String> modifiers = new ArrayList<String>();
for (Object modifier : node.modifiers()) {
modifiers.add(modifier.toString());
}
method.setModifiers(modifiers);
if (node.getBody() != null) {
MethodVisitor visitor = new MethodVisitor();
node.getBody().accept(visitor);
method.setMaxDepth(visitor.getMaxDepth());
method.setStatements(visitor.getStatements());
} else {
method.setStatements(new ArrayList<AbstractStatement>());
}
if (node.getReturnType2() != null) {
ITypeBinding bind = node.getReturnType2().resolveBinding();
if (bind != null)
method.setReturnType(bind.getQualifiedName());
}
method.setStartPosition(node.getStartPosition());
method.setEndPosition(node.getStartPosition() + node.getLength() - 1);
methods.add(method);
return true;
}
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();
}
}
@Override
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
ASTNode boundNode= astRoot.findDeclaringNode(fBinding);
ASTNode declNode= null;
if (boundNode != null) {
declNode= boundNode; // is same CU
} else {
//setSelectionDescription(selectionDescription);
CompilationUnit newRoot= ASTResolving.createQuickFixAST(getCompilationUnit(), null);
declNode= newRoot.findDeclaringNode(fBinding.getKey());
}
if (declNode != null) {
AST ast= declNode.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
if (declNode.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment)declNode;
ASTNode parent= declNode.getParent();
if (parent instanceof FieldDeclaration) {
FieldDeclaration fieldDecl= (FieldDeclaration) parent;
if (fieldDecl.fragments().size() > 1 && (fieldDecl.getParent() instanceof AbstractTypeDeclaration)) { // split
VariableDeclarationRewrite.rewriteModifiers(fieldDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, null);
return rewrite;
}
} else if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent;
if (varDecl.fragments().size() > 1 && (varDecl.getParent() instanceof Block)) { // split
VariableDeclarationRewrite.rewriteModifiers(varDecl, new VariableDeclarationFragment[] {fragment}, fIncludedModifiers, fExcludedModifiers, rewrite, null);
return rewrite;
}
} else if (parent instanceof VariableDeclarationExpression) {
// can't separate
}
declNode= parent;
} else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) {
MethodDeclaration methodDecl= (MethodDeclaration) declNode;
if (!methodDecl.isConstructor()) {
IMethodBinding methodBinding= methodDecl.resolveBinding();
if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) {
// add body
ICompilationUnit unit= getCompilationUnit();
String delimiter= unit.findRecommendedLineSeparator();
String bodyStatement= ""; //$NON-NLS-1$
Block body= ast.newBlock();
rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null);
Type returnType= methodDecl.getReturnType2();
if (returnType != null) {
Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true));
}
}
String placeHolder= CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter);
if (placeHolder != null) {
ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT);
body.statements().add(todoNode);
}
}
}
}
ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declNode);
PositionInformation trackedDeclNode= listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null);
LinkedProposalPositionGroup positionGroup= new LinkedProposalPositionGroup("group"); //$NON-NLS-1$
positionGroup.addPosition(trackedDeclNode);
getLinkedProposalModel().addPositionGroup(positionGroup);
if (boundNode != null) {
// only set end position if in same CU
setEndPosition(rewrite.track(fNode));
}
return rewrite;
}
return null;
}
@Override
public final void endVisit(final MethodDeclaration node) {
fCurrentMethods.pop();
final IMethodBinding binding= node.resolveBinding();
if (binding != null) {
if (!binding.isConstructor()) {
final Type type= node.getReturnType2();
if (type != null) {
final ConstraintVariable2 first= fModel.createReturnTypeVariable(binding);
final ConstraintVariable2 second= (ConstraintVariable2) type.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
if (first != null) {
if (second != null)
fModel.createEqualityConstraint(first, second);
endVisit(binding);
}
}
}
ConstraintVariable2 ancestor= null;
ConstraintVariable2 descendant= null;
IVariableBinding variable= null;
final List<SingleVariableDeclaration> parameters= node.parameters();
if (!parameters.isEmpty()) {
final Collection<IMethodBinding> originals= getOriginalMethods(binding);
SingleVariableDeclaration declaration= null;
for (int index= 0; index < parameters.size(); index++) {
declaration= parameters.get(index);
ancestor= fModel.createMethodParameterVariable(binding, index);
if (ancestor != null) {
descendant= (ConstraintVariable2) declaration.getType().getProperty(PROPERTY_CONSTRAINT_VARIABLE);
if (descendant != null)
fModel.createEqualityConstraint(descendant, ancestor);
variable= declaration.resolveBinding();
if (variable != null) {
descendant= fModel.createVariableVariable(variable);
if (descendant != null)
fModel.createEqualityConstraint(ancestor, descendant);
}
IMethodBinding method= null;
for (final Iterator<IMethodBinding> iterator= originals.iterator(); iterator.hasNext();) {
method= iterator.next();
if (!method.getKey().equals(binding.getKey())) {
descendant= fModel.createMethodParameterVariable(method, index);
if (descendant != null)
fModel.createEqualityConstraint(ancestor, descendant);
}
}
}
}
}
final List<Type> exceptions= node.thrownExceptionTypes();
if (!exceptions.isEmpty()) {
final ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
if (throwable != null) {
ancestor= fModel.createImmutableTypeVariable(throwable);
if (ancestor != null) {
Type exception= null;
for (int index= 0; index < exceptions.size(); index++) {
exception= exceptions.get(index);
descendant= (ConstraintVariable2) exception.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
if (descendant != null)
fModel.createSubtypeConstraint(descendant, ancestor);
}
}
}
}
}
}
private void setUpMethodFromMethodDeclaration(Method method, MethodDeclaration node) {
if (node.getReturnType2() != null)
method.setDeclaredType(ensureTypeFromDomType(node.getReturnType2()));
}