JavaParser Source Viewer

Home|JavaParser/com/github/javaparser/ast/body/VariableDeclarator.java
1/*
2 * Copyright (C) 2007-2010 JĂșlio Vilmar Gesser.
3 * Copyright (C) 2011, 2013-2020 The JavaParser Team.
4 *
5 * This file is part of JavaParser.
6 *
7 * JavaParser can be used either under the terms of
8 * a) the GNU Lesser General Public License as published by
9 *     the Free Software Foundation, either version 3 of the License, or
10 *     (at your option) any later version.
11 * b) the terms of the Apache License
12 *
13 * You should have received a copy of both licenses in LICENCE.LGPL and
14 * LICENCE.APACHE. Please refer to those files for details.
15 *
16 * JavaParser is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU Lesser General Public License for more details.
20 */
21package com.github.javaparser.ast.body;
22
23import com.github.javaparser.ast.AllFieldsConstructor;
24import com.github.javaparser.ast.Node;
25import com.github.javaparser.ast.expr.Expression;
26import com.github.javaparser.ast.expr.NameExpr;
27import com.github.javaparser.ast.expr.SimpleName;
28import com.github.javaparser.ast.nodeTypes.NodeWithSimpleName;
29import com.github.javaparser.ast.nodeTypes.NodeWithType;
30import com.github.javaparser.ast.nodeTypes.NodeWithVariables;
31import com.github.javaparser.ast.observer.AstObserverAdapter;
32import com.github.javaparser.ast.observer.ObservableProperty;
33import com.github.javaparser.ast.type.ClassOrInterfaceType;
34import com.github.javaparser.ast.type.Type;
35import com.github.javaparser.ast.visitor.CloneVisitor;
36import com.github.javaparser.ast.visitor.GenericVisitor;
37import com.github.javaparser.ast.visitor.VoidVisitor;
38import com.github.javaparser.metamodel.JavaParserMetaModel;
39import com.github.javaparser.metamodel.NonEmptyProperty;
40import com.github.javaparser.metamodel.OptionalProperty;
41import com.github.javaparser.metamodel.VariableDeclaratorMetaModel;
42import java.util.LinkedList;
43import java.util.List;
44import java.util.Optional;
45import static com.github.javaparser.utils.Utils.assertNonEmpty;
46import static com.github.javaparser.utils.Utils.assertNotNull;
47import com.github.javaparser.TokenRange;
48import com.github.javaparser.resolution.Resolvable;
49import com.github.javaparser.resolution.declarations.ResolvedValueDeclaration;
50import com.github.javaparser.ast.Generated;
51
52/**
53 * The declaration of a variable.<br>In {@code int x = 14, y = 3;} "int x = 14"  and "int y = 3"  are
54 * VariableDeclarators.
55 * <p/>The type is on all of the variable declarators because, thanks to array brackets, each variable can have a different type.
56 *
57 * @author Julio Vilmar Gesser
58 */
59public class VariableDeclarator extends Node implements NodeWithType<VariableDeclaratorType>, NodeWithSimpleName<VariableDeclarator>, Resolvable<ResolvedValueDeclaration> {
60
61    private SimpleName name;
62
63    @OptionalProperty
64    @NonEmptyProperty
65    private Expression initializer;
66
67    private Type type;
68
69    public VariableDeclarator() {
70        this(null, new ClassOrInterfaceType(), new SimpleName(), null);
71    }
72
73    public VariableDeclarator(Type typeString variableName) {
74        this(nulltype, new SimpleName(variableName), null);
75    }
76
77    public VariableDeclarator(Type typeSimpleName name) {
78        this(nulltypenamenull);
79    }
80
81    public VariableDeclarator(Type typeString variableNameExpression initializer) {
82        this(nulltype, new SimpleName(variableName), initializer);
83    }
84
85    /**
86     * Defines the declaration of a variable.
87     *
88     * @param name The identifier for this variable. IE. The variables name.
89     * @param initializer What this variable should be initialized to. An {@link com.github.javaparser.ast.expr.AssignExpr}
90     * is unnecessary as the {@code =} operator is already added.
91     */
92    @AllFieldsConstructor
93    public VariableDeclarator(Type typeSimpleName nameExpression initializer) {
94        this(nulltypenameinitializer);
95    }
96
97    /**
98     * This constructor is used by the parser and is considered private.
99     */
100    @Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
101    public VariableDeclarator(TokenRange tokenRangeType typeSimpleName nameExpression initializer) {
102        super(tokenRange);
103        setType(type);
104        setName(name);
105        setInitializer(initializer);
106        customInitialization();
107    }
108
109    @Override
110    protected void customInitialization() {
111        // We register an observer on the type property. When it is changed the MaximumCommonType is changes as well,
112        // because it is derived from the type of the variables it contains, for this reason we notify about the change
113        register(new AstObserverAdapter() {
114
115            @Override
116            public void propertyChange(Node observedNodeObservableProperty propertyObject oldValueObject newValue) {
117                if (property == ObservableProperty.TYPE) {
118                    VariableDeclarator vd = VariableDeclarator.this;
119                    if (vd.getParentNode().isPresent() && vd.getParentNode().get() instanceof NodeWithVariables) {
120                        NodeWithVariables<?> nodeWithVariables = (NodeWithVariables<?>) vd.getParentNode().get();
121                        // We calculate the value the property will assume after the change will be completed
122                        Optional<TypecurrentMaxCommonType = nodeWithVariables.getMaximumCommonType();
123                        List<Typetypes = new LinkedList<>();
124                        int index = nodeWithVariables.getVariables().indexOf(vd);
125                        for (int i = 0i < nodeWithVariables.getVariables().size(); i++) {
126                            if (i == index) {
127                                types.add((TypenewValue);
128                            } else {
129                                types.add(nodeWithVariables.getVariable(i).getType());
130                            }
131                        }
132                        Optional<TypenewMaxCommonType = NodeWithVariables.calculateMaximumCommonType(types);
133                        ((NodenodeWithVariables).notifyPropertyChange(ObservableProperty.MAXIMUM_COMMON_TYPEcurrentMaxCommonType.orElse(null), newMaxCommonType.orElse(null));
134                    }
135                }
136            }
137        });
138    }
139
140    @Override
141    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
142    public <RAR accept(final GenericVisitor<RAvfinal A arg) {
143        return v.visit(this, arg);
144    }
145
146    @Override
147    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
148    public <Avoid accept(final VoidVisitor<Avfinal A arg) {
149        v.visit(this, arg);
150    }
151
152    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
153    public Optional<ExpressiongetInitializer() {
154        return Optional.ofNullable(initializer);
155    }
156
157    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
158    public SimpleName getName() {
159        return name;
160    }
161
162    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
163    public VariableDeclarator setName(final SimpleName name) {
164        assertNotNull(name);
165        if (name == this.name) {
166            return (VariableDeclarator) this;
167        }
168        notifyPropertyChange(ObservableProperty.NAME, this.namename);
169        if (this.name != null)
170            this.name.setParentNode(null);
171        this.name = name;
172        setAsParentNodeOf(name);
173        return this;
174    }
175
176    /**
177     * Sets the initializer expression
178     *
179     * @param initializer the initializer expression, can be null
180     * @return this, the VariableDeclarator
181     */
182    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
183    public VariableDeclarator setInitializer(final Expression initializer) {
184        if (initializer == this.initializer) {
185            return (VariableDeclarator) this;
186        }
187        notifyPropertyChange(ObservableProperty.INITIALIZER, this.initializerinitializer);
188        if (this.initializer != null)
189            this.initializer.setParentNode(null);
190        this.initializer = initializer;
191        setAsParentNodeOf(initializer);
192        return this;
193    }
194
195    /**
196     * Will create a {@link NameExpr} with the initializer param
197     *
198     * @param init the initializer expression, can be null
199     * @return this, the VariableDeclarator
200     */
201    public VariableDeclarator setInitializer(String init) {
202        return setInitializer(new NameExpr(assertNonEmpty(init)));
203    }
204
205    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
206    public Type getType() {
207        return type;
208    }
209
210    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
211    public VariableDeclarator setType(final Type type) {
212        assertNotNull(type);
213        if (type == this.type) {
214            return (VariableDeclarator) this;
215        }
216        notifyPropertyChange(ObservableProperty.TYPE, this.typetype);
217        if (this.type != null)
218            this.type.setParentNode(null);
219        this.type = type;
220        setAsParentNodeOf(type);
221        return this;
222    }
223
224    @Override
225    @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
226    public boolean remove(Node node) {
227        if (node == null)
228            return false;
229        if (initializer != null) {
230            if (node == initializer) {
231                removeInitializer();
232                return true;
233            }
234        }
235        return super.remove(node);
236    }
237
238    @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
239    public VariableDeclarator removeInitializer() {
240        return setInitializer((Expressionnull);
241    }
242
243    @Override
244    @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
245    public VariableDeclarator clone() {
246        return (VariableDeclaratoraccept(new CloneVisitor(), null);
247    }
248
249    @Override
250    @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
251    public VariableDeclaratorMetaModel getMetaModel() {
252        return JavaParserMetaModel.variableDeclaratorMetaModel;
253    }
254
255    @Override
256    @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
257    public boolean replace(Node nodeNode replacementNode) {
258        if (node == null)
259            return false;
260        if (initializer != null) {
261            if (node == initializer) {
262                setInitializer((ExpressionreplacementNode);
263                return true;
264            }
265        }
266        if (node == name) {
267            setName((SimpleNamereplacementNode);
268            return true;
269        }
270        if (node == type) {
271            setType((TypereplacementNode);
272            return true;
273        }
274        return super.replace(nodereplacementNode);
275    }
276
277    @Override
278    public ResolvedValueDeclaration resolve() {
279        return getSymbolResolver().resolveDeclaration(this, ResolvedValueDeclaration.class);
280    }
281}
282
MembersX
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:Block:nodeWithVariables
VariableDeclarator:setType
VariableDeclarator:getType
VariableDeclarator:setInitializer
VariableDeclarator:type
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:vd
VariableDeclarator:clone
VariableDeclarator:accept
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:Block:index
VariableDeclarator:name
VariableDeclarator:setName
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:Block:types
VariableDeclarator:customInitialization:Block:propertyChange
VariableDeclarator:resolve
VariableDeclarator:VariableDeclarator
VariableDeclarator:removeInitializer
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:Block:currentMaxCommonType
VariableDeclarator:initializer
VariableDeclarator:customInitialization
VariableDeclarator:getInitializer
VariableDeclarator:getName
VariableDeclarator:getMetaModel
VariableDeclarator:replace
VariableDeclarator:customInitialization:Block:propertyChange:Block:Block:Block:newMaxCommonType
VariableDeclarator:remove
Members
X