use of org.eclipse.jdt.internal.corext.codemanipulation.AddCustomConstructorOperation in project eclipse.jdt.ls by eclipse.
the class GenerateConstructorsHandler method generateConstructors.
public static TextEdit generateConstructors(IType type, LspMethodBinding[] constructors, LspVariableBinding[] fields, CodeGenerationSettings settings, Range cursor, IProgressMonitor monitor) {
if (type == null || type.getCompilationUnit() == null || constructors == null || constructors.length == 0) {
return null;
}
try {
CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(type.getCompilationUnit(), CoreASTProvider.WAIT_YES, monitor);
if (astRoot == null) {
return null;
}
ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
if (typeBinding != null) {
ASTNode declarationNode = null;
if (cursor != null) {
ASTNode node = NodeFinder.perform(astRoot, DiagnosticsHelper.getStartOffset(type.getCompilationUnit(), cursor), DiagnosticsHelper.getLength(type.getCompilationUnit(), cursor));
declarationNode = SourceAssistProcessor.getTypeDeclarationNode(node);
}
// If cursor position is not specified, then insert to the last by default.
IJavaElement insertPosition = (declarationNode != null) ? CodeGenerationUtils.findInsertElementAfterLastField(type) : CodeGenerationUtils.findInsertElement(type, cursor);
Map<String, IVariableBinding> fieldBindings = new HashMap<>();
for (IVariableBinding binding : typeBinding.getDeclaredFields()) {
fieldBindings.put(binding.getKey(), binding);
}
IVariableBinding[] selectedFields = Arrays.stream(fields).map(field -> fieldBindings.get(field.bindingKey)).filter(binding -> binding != null).toArray(IVariableBinding[]::new);
IMethodBinding[] superConstructors = getVisibleConstructors(astRoot, typeBinding);
TextEdit textEdit = new MultiTextEdit();
for (LspMethodBinding constructor : constructors) {
Optional<IMethodBinding> selectedSuperConstructor = Arrays.stream(superConstructors).filter(superConstructor -> compareConstructor(superConstructor, constructor)).findAny();
if (selectedSuperConstructor.isPresent()) {
IMethodBinding superConstructor = selectedSuperConstructor.get();
AddCustomConstructorOperation constructorOperation = new AddCustomConstructorOperation(astRoot, typeBinding, selectedFields, superConstructor, insertPosition, settings, false, false);
constructorOperation.setOmitSuper(superConstructor.getParameterTypes().length == 0);
constructorOperation.setVisibility(typeBinding.isEnum() ? Modifier.PRIVATE : Modifier.PUBLIC);
constructorOperation.run(null);
textEdit.addChild(constructorOperation.getResultingEdit());
}
}
return textEdit;
}
} catch (CoreException e) {
JavaLanguageServerPlugin.logException("Failed to generate constructors", e);
}
return null;
}
Aggregations