下面列出了怎么用org.eclipse.jdt.core.dom.SingleVariableDeclaration的API类实例代码及写法,或者点击链接到github查看源代码。
private String getSignature(MethodDeclaration node) {
StringBuffer buffer= new StringBuffer();
buffer.append(node.getName().toString());
buffer.append('(');
boolean first= true;
Iterator<SingleVariableDeclaration> iterator= node.parameters().iterator();
while (iterator.hasNext()) {
SingleVariableDeclaration svd= iterator.next();
if (!first)
buffer.append(", "); //$NON-NLS-1$
buffer.append(getType(svd.getType()));
if (svd.isVarargs())
buffer.append("..."); //$NON-NLS-1$
first= false;
}
buffer.append(')');
return buffer.toString();
}
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$
}
@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;
}
private void initializeParameterInfos() {
IVariableBinding[] arguments= fAnalyzer.getArguments();
fParameterInfos= new ArrayList<ParameterInfo>(arguments.length);
ASTNode root= fAnalyzer.getEnclosingBodyDeclaration();
ParameterInfo vararg= null;
for (int i= 0; i < arguments.length; i++) {
IVariableBinding argument= arguments[i];
if (argument == null)
continue;
VariableDeclaration declaration= ASTNodes.findVariableDeclaration(argument, root);
boolean isVarargs= declaration instanceof SingleVariableDeclaration
? ((SingleVariableDeclaration)declaration).isVarargs()
: false;
ParameterInfo info= new ParameterInfo(argument, getType(declaration, isVarargs), argument.getName(), i);
if (isVarargs) {
vararg= info;
} else {
fParameterInfos.add(info);
}
}
if (vararg != null) {
fParameterInfos.add(vararg);
}
}
boolean isExceptionCaught(ITypeBinding excpetionType) {
for (Iterator<List<CatchClause>> exceptions= fExceptionStack.iterator(); exceptions.hasNext(); ) {
for (Iterator<CatchClause> catchClauses= exceptions.next().iterator(); catchClauses.hasNext(); ) {
SingleVariableDeclaration caughtException= catchClauses.next().getException();
IVariableBinding binding= caughtException.resolveBinding();
if (binding == null)
continue;
ITypeBinding caughtype= binding.getType();
while (caughtype != null) {
if (caughtype == excpetionType)
return true;
caughtype= caughtype.getSuperclass();
}
}
}
return false;
}
private SimpleName addSourceClassParameterToMovedMethod(MethodDeclaration newMethodDeclaration, ASTRewrite targetRewriter) {
AST ast = newMethodDeclaration.getAST();
SingleVariableDeclaration parameter = ast.newSingleVariableDeclaration();
SimpleName typeName = ast.newSimpleName(sourceTypeDeclaration.getName().getIdentifier());
Type parameterType = ast.newSimpleType(typeName);
targetRewriter.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, parameterType, null);
String sourceTypeName = sourceTypeDeclaration.getName().getIdentifier();
SimpleName parameterName = ast.newSimpleName(sourceTypeName.replaceFirst(Character.toString(sourceTypeName.charAt(0)), Character.toString(Character.toLowerCase(sourceTypeName.charAt(0)))));
targetRewriter.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, parameterName, null);
ListRewrite parametersRewrite = targetRewriter.getListRewrite(newMethodDeclaration, MethodDeclaration.PARAMETERS_PROPERTY);
parametersRewrite.insertLast(parameter, null);
this.additionalArgumentsAddedToMovedMethod.add("this");
this.additionalTypeBindingsToBeImportedInTargetClass.add(sourceTypeDeclaration.resolveBinding());
addParamTagElementToJavadoc(newMethodDeclaration, targetRewriter, parameterName.getIdentifier());
setPublicModifierToSourceTypeDeclaration();
return parameterName;
}
/**
* @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;
}
private static ModifierChangeOperation createAddFinalOperation(SimpleName name, ASTNode decl) {
if (decl == null)
return null;
IBinding binding= name.resolveBinding();
if (!canAddFinal(binding, decl))
return null;
if (decl instanceof SingleVariableDeclaration) {
return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
} else if (decl instanceof VariableDeclarationExpression) {
return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
} else if (decl instanceof VariableDeclarationFragment){
VariableDeclarationFragment frag= (VariableDeclarationFragment)decl;
decl= decl.getParent();
if (decl instanceof FieldDeclaration || decl instanceof VariableDeclarationStatement) {
List<VariableDeclarationFragment> list= new ArrayList<VariableDeclarationFragment>();
list.add(frag);
return new ModifierChangeOperation(decl, list, Modifier.FINAL, Modifier.NONE);
} else if (decl instanceof VariableDeclarationExpression) {
return new ModifierChangeOperation(decl, new ArrayList<VariableDeclarationFragment>(), Modifier.FINAL, Modifier.NONE);
}
}
return null;
}
public void initialize() {
Block body= fDeclaration.getBody();
// first collect the static imports. This is necessary to not mark
// static imported fields and methods as implicit visible.
fTypesToImport= new ArrayList<SimpleName>();
fStaticsToImport= new ArrayList<SimpleName>();
ImportReferencesCollector.collect(body, fTypeRoot.getJavaProject(), null, fTypesToImport, fStaticsToImport);
// Now collect implicit references and name references
body.accept(new UpdateCollector());
int numberOfLocals= LocalVariableIndex.perform(fDeclaration);
FlowContext context= new FlowContext(0, numberOfLocals + 1);
context.setConsiderAccessMode(true);
context.setComputeMode(FlowContext.MERGE);
InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(context);
FlowInfo info= flowAnalyzer.perform(getStatements());
for (Iterator<SingleVariableDeclaration> iter= fDeclaration.parameters().iterator(); iter.hasNext();) {
SingleVariableDeclaration element= iter.next();
IVariableBinding binding= element.resolveBinding();
ParameterData data= (ParameterData)element.getProperty(ParameterData.PROPERTY);
data.setAccessMode(info.getAccessMode(context, binding));
}
}
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;
}
/**
* @return an array containing the argument names for the constructor
* identified by <code>fCtorBinding</code>, if available, or default
* names if unavailable (e.g. if the constructor resides in a binary unit).
*/
private String[] findCtorArgNames() {
int numArgs= fCtorBinding.getParameterTypes().length;
String[] names= new String[numArgs];
CompilationUnit ctorUnit= (CompilationUnit) ASTNodes.getParent(fCtorOwningClass, CompilationUnit.class);
MethodDeclaration ctorDecl= (MethodDeclaration) ctorUnit.findDeclaringNode(fCtorBinding.getKey());
if (ctorDecl != null) {
List<SingleVariableDeclaration> formalArgs= ctorDecl.parameters();
int i= 0;
for(Iterator<SingleVariableDeclaration> iter= formalArgs.iterator(); iter.hasNext(); i++) {
SingleVariableDeclaration svd= iter.next();
names[i]= svd.getName().getIdentifier();
}
return names;
}
// Have no way of getting the formal argument names; just fake it.
for(int i=0; i < numArgs; i++)
names[i]= "arg" + (i+1); //$NON-NLS-1$
return names;
}
/**
* Add argument-related features.
*
* @param md
* @param features
*/
private void addArgumentFeatures(final MethodDeclaration md,
final Set<String> features) {
checkArgument(activeFeatures.contains(AvailableFeatures.ARGUMENTS));
features.add("nParams:" + md.parameters().size());
for (int i = 0; i < md.parameters().size(); i++) {
final SingleVariableDeclaration varDecl = (SingleVariableDeclaration) md
.parameters().get(i);
features.add("param" + i + "Type:" + varDecl.getType().toString());
for (final String namepart : JavaFeatureExtractor
.getNameParts(varDecl.getName().toString())) {
features.add("paramName:" + namepart);
}
}
if (md.isVarargs()) {
features.add("isVarArg");
}
}
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
}
}
}
}
}
public static SimpleName isGetter(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() == 0) {
Statement statement = statements.get(0);
if(statement instanceof ReturnStatement) {
ReturnStatement returnStatement = (ReturnStatement)statement;
Expression returnStatementExpression = returnStatement.getExpression();
if(returnStatementExpression instanceof SimpleName) {
return (SimpleName)returnStatementExpression;
}
else if(returnStatementExpression instanceof FieldAccess) {
FieldAccess fieldAccess = (FieldAccess)returnStatementExpression;
return fieldAccess.getName();
}
}
}
}
return null;
}
private SuperConstructorInvocation addEnclosingInstanceAccess(ASTRewrite rewrite, ImportRewriteContext importRewriteContext, List<SingleVariableDeclaration> parameters, String[] paramNames, ITypeBinding enclosingInstance) {
AST ast= rewrite.getAST();
SuperConstructorInvocation invocation= ast.newSuperConstructorInvocation();
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setType(getImportRewrite().addImport(enclosingInstance, ast, importRewriteContext, TypeLocation.PARAMETER));
String[] enclosingArgNames= StubUtility.getArgumentNameSuggestions(getCompilationUnit().getJavaProject(), enclosingInstance.getTypeDeclaration().getName(), 0, paramNames);
String firstName= enclosingArgNames[0];
var.setName(ast.newSimpleName(firstName));
parameters.add(var);
Name enclosing= ast.newSimpleName(firstName);
invocation.setExpression(enclosing);
String key= "arg_name_" + firstName; //$NON-NLS-1$
addLinkedPosition(rewrite.track(enclosing), false, key);
for (int i= 0; i < enclosingArgNames.length; i++) {
addLinkedPositionProposal(key, enclosingArgNames[i]); // alternative names
}
return invocation;
}
/**
* The selection corresponds to a ParameterizedType (return type of method)
* @param pt the type
* @return the message
*/
private String parameterizedTypeSelected(ParameterizedType pt) {
ASTNode parent= pt.getParent();
if (parent.getNodeType() == ASTNode.METHOD_DECLARATION){
fMethodBinding= ((MethodDeclaration)parent).resolveBinding();
fParamIndex= -1;
fEffectiveSelectionStart= pt.getStartPosition();
fEffectiveSelectionLength= pt.getLength();
setOriginalType(pt.resolveBinding());
} else if (parent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION){
return singleVariableDeclarationSelected((SingleVariableDeclaration)parent);
} else if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){
return variableDeclarationStatementSelected((VariableDeclarationStatement)parent);
} else if (parent.getNodeType() == ASTNode.FIELD_DECLARATION){
return fieldDeclarationSelected((FieldDeclaration)parent);
} else {
return nodeTypeNotSupported();
}
return null;
}
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode,
Collection<ChangeCorrectionProposal> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL,
simpleName, null, relevance));
}
}
}
}
}
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
AST ast= rewrite.getAST();
List<Expression> arguments= fArguments;
for (int i= 0; i < arguments.size(); i++) {
Expression elem= arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
// argument type
String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
Type type= evaluateParameterType(ast, elem, argTypeKey, context);
param.setType(type);
// argument name
String argNameKey= "arg_name_" + i; //$NON-NLS-1$
String name= evaluateParameterName(takenNames, elem, type, argNameKey);
param.setName(ast.newSimpleName(name));
params.add(param);
}
}
@Override
public ITypeConstraint[] create(CatchClause node) {
SingleVariableDeclaration exception= node.getException();
ConstraintVariable nameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(exception.getName(), getContext());
ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
nameVariable,
fConstraintVariableFactory.makeTypeVariable(exception.getType()));
ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$
ITypeConstraint[] catchBound= fTypeConstraintFactory.createSubtypeConstraint(
nameVariable,
fConstraintVariableFactory.makeRawBindingVariable(throwable));
ArrayList<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
result.addAll(Arrays.asList(defines));
result.addAll(Arrays.asList(catchBound));
return result.toArray(new ITypeConstraint[result.size()]);
}
@Override
public ITypeConstraint[] create(SingleVariableDeclaration svd){
ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()),
fConstraintVariableFactory.makeTypeVariable(svd.getType()));
if (svd.getInitializer() == null)
return defines;
ITypeConstraint[] constraints = fTypeConstraintFactory.createSubtypeConstraint(
fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getInitializer(), getContext()),
fConstraintVariableFactory.makeExpressionOrTypeVariable(svd.getName(), getContext()));
if (defines.length == 0 && constraints.length == 0){
return new ITypeConstraint[0];
} else if (defines.length == 0){
return constraints;
} else if (constraints.length == 0){
return defines;
} else {
List<ITypeConstraint> all= new ArrayList<ITypeConstraint>();
all.addAll(Arrays.asList(defines));
all.addAll(Arrays.asList(constraints));
return (ITypeConstraint[])all.toArray();
}
}
private void checkConstructor(MethodDeclaration elem) {
for (Object obj : elem.parameters()) {
SingleVariableDeclaration param = (SingleVariableDeclaration) obj;
if (!Utils.isAllowedAttributeType(param.getType().resolveBinding(), false)) {
collector.report(INVALID_ATTRIBUTE_TYPE.create(collector.getSourceInfo(), param.getType()));
}
}
// TODO: check constructor body
}
@Override
public boolean visit(final SingleVariableDeclaration node) {
final IdentifierInformation vd = new IdentifierInformation(SHA,
file, node.getName().getIdentifier(), node.getType()
.toString().toString(), getLineNumber(node),
getAstParentString(node));
identifiers.add(vd);
return super.visit(node);
}
@Override
public void endVisit(SingleVariableDeclaration node) {
// used for formal method parameters and catch clauses
//TODO: extra dimensions?
// ConstraintVariable2 typeCv= getConstraintVariable(node.getType()); //TODO: who needs this?
// ConstraintVariable2 nameCv;
// switch (node.getParent().getNodeType()) {
// case ASTNode.METHOD_DECLARATION :
// MethodDeclaration parent= (MethodDeclaration) node.getParent();
// int index= parent.parameters().indexOf(node);
// nameCv= fTCFactory.makeParameterTypeVariable(parent.resolveBinding(), index, node.getType());
// //store source range even if variable not used in constraint here. TODO: move to visit(MethodDeclaration)?
// break;
// case ASTNode.CATCH_CLAUSE :
// nameCv= fTCFactory.makeVariableVariable(node.resolveBinding());
//
// break;
// default:
// unexpectedNode(node.getParent());
// }
// setConstraintVariable(node, nameCv);
//TODO: Move this into visit(SimpleName) or leave it here?
// ExpressionVariable2 name= fTCFactory.makeExpressionVariable(node.getName());
// TypeVariable2 type= fTCFactory.makeTypeVariable(node.getType());
// ITypeConstraint2[] nameEqualsType= fTCFactory.createEqualsConstraint(name, type);
// addConstraints(nameEqualsType);
//TODO: When can a SingleVariableDeclaration have an initializer? Never up to Java 1.5?
Expression initializer= node.getInitializer();
if (initializer == null)
return;
// ConstraintVariable2 initializerCv= getConstraintVariable(initializer);
// ConstraintVariable2 nameCv= getConstraintVariable(node);
//TODO: check: property has been set in visit(CatchClause), visit(MethodDeclaration), visit(EnhancedForStatament)
//fTCFactory.createSubtypeConstraint(initializerCv, nameCv); //TODO: not for augment raw container clients
}
private static boolean isExplicitlyTypedLambda(Expression expression) {
if (!(expression instanceof LambdaExpression))
return false;
LambdaExpression lambda= (LambdaExpression) expression;
List<VariableDeclaration> parameters= lambda.parameters();
if (parameters.isEmpty())
return true;
return parameters.get(0) instanceof SingleVariableDeclaration;
}
private boolean isParameter(ParameterInfo pi, ASTNode node, List<SingleVariableDeclaration> enclosingMethodParameters, String qualifier) {
if (node instanceof Name) {
Name name= (Name) node;
IVariableBinding binding= ASTNodes.getVariableBinding(name);
if (binding != null && binding.isParameter()) {
return binding.getName().equals(getNameInScope(pi, enclosingMethodParameters));
} else {
if (node instanceof QualifiedName) {
QualifiedName qn= (QualifiedName) node;
return qn.getFullyQualifiedName().equals(JavaModelUtil.concatenateName(qualifier, getNameInScope(pi, enclosingMethodParameters)));
}
}
}
return false;
}
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);
}
private void createConstructor(final AbstractTypeDeclaration declaration, final ASTRewrite rewrite) throws CoreException {
Assert.isNotNull(declaration);
Assert.isNotNull(rewrite);
final AST ast= declaration.getAST();
final MethodDeclaration constructor= ast.newMethodDeclaration();
constructor.setConstructor(true);
constructor.setName(ast.newSimpleName(declaration.getName().getIdentifier()));
final String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), fType.getElementName(), fType.getElementName(), getNewConstructorParameterNames(), new String[0], null, null, StubUtility.getLineDelimiterUsed(fType.getJavaProject()));
if (comment != null && comment.length() > 0) {
final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
constructor.setJavadoc(doc);
}
if (fCreateInstanceField) {
final SingleVariableDeclaration variable= ast.newSingleVariableDeclaration();
final String name= getNameForEnclosingInstanceConstructorParameter();
variable.setName(ast.newSimpleName(name));
variable.setType(createEnclosingType(ast));
constructor.parameters().add(variable);
final Block body= ast.newBlock();
final Assignment assignment= ast.newAssignment();
if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
final FieldAccess access= ast.newFieldAccess();
access.setExpression(ast.newThisExpression());
access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
assignment.setLeftHandSide(access);
} else
assignment.setLeftHandSide(ast.newSimpleName(fEnclosingInstanceFieldName));
assignment.setRightHandSide(ast.newSimpleName(name));
final Statement statement= ast.newExpressionStatement(assignment);
body.statements().add(statement);
constructor.setBody(body);
} else
constructor.setBody(ast.newBlock());
rewrite.getListRewrite(declaration, declaration.getBodyDeclarationsProperty()).insertFirst(constructor, null);
}
private 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();
}
/**
* Creates and adds the necessary argument declarations to the given factory method.<br>
* An argument is needed for each original constructor argument for which the
* evaluation of the actual arguments across all calls was not able to be
* pushed inside the factory method (e.g. arguments with side-effects, references
* to fields if the factory method is to be static or reside in a factory class,
* or arguments that varied across the set of constructor calls).<br>
* <code>fArgTypes</code> identifies such arguments by a <code>null</code> value.
* @param ast utility object used to create AST nodes
* @param newMethod the <code>MethodDeclaration</code> for the factory method
*/
private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) {
List<SingleVariableDeclaration> argDecls= newMethod.parameters();
for(int i=0; i < fArgTypes.length; i++) {
SingleVariableDeclaration argDecl= ast.newSingleVariableDeclaration();
Type argType;
if (i == (fArgTypes.length - 1) && fCtorIsVarArgs) {
// The trailing varargs arg has an extra array dimension, compared to
// what we need to pass to setType()...
argType= typeNodeForTypeBinding(fArgTypes[i].getElementType(),
fArgTypes[i].getDimensions()-1, ast);
argDecl.setVarargs(true);
} else
argType= typeNodeForTypeBinding(fArgTypes[i], 0, ast);
argDecl.setName(ast.newSimpleName(fFormalArgNames[i]));
argDecl.setType(argType);
argDecls.add(argDecl);
}
ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes();
List<Type> exceptions= newMethod.thrownExceptionTypes();
for(int i=0; i < ctorExcepts.length; i++) {
exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast));
}
copyTypeParameters(ast, newMethod);
}
private SuperSetterBasedBuilderField createBuilderField(MethodDeclaration method) {
String methodName = method.getName().toString();
String upperCamelCaseFieldName = methodName.replaceFirst(SETTER_METHOD_PREFIX, "");
String fieldName = camelCaseConverter.toLowerCamelCase(upperCamelCaseFieldName);
SingleVariableDeclaration parameter = (SingleVariableDeclaration) method.parameters().get(0);
return SuperSetterBasedBuilderField.builder()
.withBuilderFieldName(fieldName)
.withOriginalFieldName(fieldName)
.withFieldType(parameter.getType())
.withSetterName(methodName)
.build();
}