0
# Core Parsing
1
2
JavaParser provides comprehensive parsing capabilities for Java source code from version 1.0 through 21. The library offers both static methods for simple parsing and configurable parsers for advanced use cases.
3
4
## Capabilities
5
6
### Static Parsing Methods
7
8
Simple static methods for parsing Java code without configuration. These methods throw exceptions on parsing errors.
9
10
```java { .api }
11
/**
12
* Parse a complete Java source file from string
13
* @param code Java source code to parse
14
* @return CompilationUnit representing the parsed code
15
* @throws ParseProblemException if parsing fails
16
*/
17
public static CompilationUnit parse(String code);
18
19
/**
20
* Parse a complete Java source file from File
21
* @param file File containing Java source code
22
* @return CompilationUnit representing the parsed code
23
* @throws FileNotFoundException if file doesn't exist
24
* @throws ParseProblemException if parsing fails
25
*/
26
public static CompilationUnit parse(File file) throws FileNotFoundException;
27
28
/**
29
* Parse a complete Java source file from InputStream
30
* @param in InputStream containing Java source code
31
* @return CompilationUnit representing the parsed code
32
* @throws ParseProblemException if parsing fails
33
*/
34
public static CompilationUnit parse(InputStream in);
35
36
/**
37
* Parse Java source file from InputStream with encoding
38
* @param in InputStream containing Java source code
39
* @param encoding Character encoding of the source
40
* @return CompilationUnit representing the parsed code
41
* @throws ParseProblemException if parsing fails
42
*/
43
public static CompilationUnit parse(InputStream in, Charset encoding);
44
```
45
46
**Usage Examples:**
47
48
```java
49
import com.github.javaparser.StaticJavaParser;
50
import com.github.javaparser.ast.CompilationUnit;
51
52
// Parse from string
53
String code = "public class Hello { public void world() {} }";
54
CompilationUnit cu = StaticJavaParser.parse(code);
55
56
// Parse from file
57
File javaFile = new File("Example.java");
58
CompilationUnit cu2 = StaticJavaParser.parse(javaFile);
59
60
// Parse from classpath resource
61
InputStream is = getClass().getResourceAsStream("/Example.java");
62
CompilationUnit cu3 = StaticJavaParser.parse(is);
63
```
64
65
### Expression Parsing
66
67
Parse individual Java expressions, statements, and other language constructs.
68
69
```java { .api }
70
/**
71
* Parse a Java expression
72
* @param expression String containing Java expression
73
* @return Expression AST node
74
* @throws ParseProblemException if parsing fails
75
*/
76
public static <T extends Expression> T parseExpression(String expression);
77
78
/**
79
* Parse a Java statement
80
* @param statement String containing Java statement
81
* @return Statement AST node
82
* @throws ParseProblemException if parsing fails
83
*/
84
public static Statement parseStatement(String statement);
85
86
/**
87
* Parse a block statement
88
* @param blockStatement String containing Java block statement
89
* @return BlockStmt AST node
90
* @throws ParseProblemException if parsing fails
91
*/
92
public static BlockStmt parseBlock(String blockStatement);
93
94
/**
95
* Parse an import declaration
96
* @param importDeclaration String containing import statement
97
* @return ImportDeclaration AST node
98
* @throws ParseProblemException if parsing fails
99
*/
100
public static ImportDeclaration parseImport(String importDeclaration);
101
```
102
103
**Usage Examples:**
104
105
```java
106
// Parse expressions
107
BinaryExpr expr = StaticJavaParser.parseExpression("x + y * 2");
108
MethodCallExpr call = StaticJavaParser.parseExpression("obj.method(arg1, arg2)");
109
ObjectCreationExpr creation = StaticJavaParser.parseExpression("new ArrayList<>()");
110
111
// Parse statements
112
IfStmt ifStmt = StaticJavaParser.parseStatement("if (x > 0) return x;");
113
ForStmt forLoop = StaticJavaParser.parseStatement("for (int i = 0; i < 10; i++) {}");
114
115
// Parse blocks
116
BlockStmt block = StaticJavaParser.parseBlock("{ int x = 5; return x * 2; }");
117
118
// Parse imports
119
ImportDeclaration imp = StaticJavaParser.parseImport("import java.util.List;");
120
```
121
122
### Type and Declaration Parsing
123
124
Parse Java type declarations, method signatures, and other declaration constructs.
125
126
```java { .api }
127
/**
128
* Parse a Java type
129
* @param type String containing type declaration
130
* @return Type AST node
131
* @throws ParseProblemException if parsing fails
132
*/
133
public static Type parseType(String type);
134
135
/**
136
* Parse a class or interface type
137
* @param type String containing class/interface type
138
* @return ClassOrInterfaceType AST node
139
* @throws ParseProblemException if parsing fails
140
*/
141
public static ClassOrInterfaceType parseClassOrInterfaceType(String type);
142
143
/**
144
* Parse a method declaration
145
* @param methodDeclaration String containing method declaration
146
* @return MethodDeclaration AST node
147
* @throws ParseProblemException if parsing fails
148
*/
149
public static MethodDeclaration parseMethodDeclaration(String methodDeclaration);
150
151
/**
152
* Parse a method parameter
153
* @param parameter String containing parameter declaration
154
* @return Parameter AST node
155
* @throws ParseProblemException if parsing fails
156
*/
157
public static Parameter parseParameter(String parameter);
158
159
/**
160
* Parse a type declaration (class, interface, enum, annotation)
161
* @param typeDeclaration String containing type declaration
162
* @return TypeDeclaration AST node
163
* @throws ParseProblemException if parsing fails
164
*/
165
public static TypeDeclaration<?> parseTypeDeclaration(String typeDeclaration);
166
```
167
168
**Usage Examples:**
169
170
```java
171
// Parse types
172
PrimitiveType intType = StaticJavaParser.parseType("int");
173
ClassOrInterfaceType listType = StaticJavaParser.parseType("List<String>");
174
ArrayType arrayType = StaticJavaParser.parseType("String[]");
175
176
// Parse method declarations
177
MethodDeclaration method = StaticJavaParser.parseMethodDeclaration(
178
"public String getName() { return name; }"
179
);
180
181
// Parse parameters
182
Parameter param = StaticJavaParser.parseParameter("final String name");
183
184
// Parse class declarations
185
ClassOrInterfaceDeclaration cls = StaticJavaParser.parseTypeDeclaration(
186
"public class Example { private String field; }"
187
);
188
```
189
190
### Configurable Parsing with JavaParser
191
192
For error handling and advanced configuration, use the JavaParser class which returns ParseResult objects.
193
194
```java { .api }
195
/**
196
* JavaParser with configurable behavior
197
*/
198
public final class JavaParser {
199
public JavaParser();
200
public JavaParser(ParserConfiguration configuration);
201
202
/**
203
* Parse with error handling
204
* @param code Java source code to parse
205
* @return ParseResult with result and any problems
206
*/
207
public ParseResult<CompilationUnit> parse(String code);
208
209
/**
210
* Parse expression with error handling
211
* @param expression Java expression to parse
212
* @return ParseResult with result and any problems
213
*/
214
public <T extends Expression> ParseResult<T> parseExpression(String expression);
215
216
/**
217
* Parse statement with error handling
218
* @param statement Java statement to parse
219
* @return ParseResult with result and any problems
220
*/
221
public ParseResult<Statement> parseStatement(String statement);
222
}
223
224
/**
225
* Result of parsing operation with error information
226
*/
227
public class ParseResult<T> {
228
/**
229
* Get parsing result if successful
230
* @return Optional containing result, empty if parsing failed
231
*/
232
public Optional<T> getResult();
233
234
/**
235
* Get list of parsing problems/errors
236
* @return List of problems encountered during parsing
237
*/
238
public List<Problem> getProblems();
239
240
/**
241
* Check if parsing was successful
242
* @return true if parsing succeeded without errors
243
*/
244
public boolean isSuccessful();
245
}
246
```
247
248
**Usage Examples:**
249
250
```java
251
import com.github.javaparser.JavaParser;
252
import com.github.javaparser.ParseResult;
253
254
JavaParser parser = new JavaParser();
255
256
// Parse with error handling
257
ParseResult<CompilationUnit> result = parser.parse("invalid java code");
258
if (result.isSuccessful()) {
259
CompilationUnit cu = result.getResult().get();
260
// Process successful parse
261
} else {
262
List<Problem> problems = result.getProblems();
263
for (Problem problem : problems) {
264
System.err.println("Parse error: " + problem.getMessage());
265
}
266
}
267
```
268
269
### Resource and Path Parsing
270
271
Parse Java source files from various sources including classpath resources and file system paths.
272
273
```java { .api }
274
/**
275
* Parse from classpath resource
276
* @param path Classpath resource path
277
* @return CompilationUnit representing the parsed code
278
* @throws IOException if resource cannot be read
279
* @throws ParseProblemException if parsing fails
280
*/
281
public static CompilationUnit parseResource(String path) throws IOException;
282
283
/**
284
* Parse from classpath resource with encoding
285
* @param path Classpath resource path
286
* @param encoding Character encoding
287
* @return CompilationUnit representing the parsed code
288
* @throws IOException if resource cannot be read
289
* @throws ParseProblemException if parsing fails
290
*/
291
public static CompilationUnit parseResource(String path, Charset encoding) throws IOException;
292
293
/**
294
* Parse from file system path
295
* @param path Path to Java source file
296
* @return CompilationUnit representing the parsed code
297
* @throws IOException if file cannot be read
298
* @throws ParseProblemException if parsing fails
299
*/
300
public static CompilationUnit parse(Path path) throws IOException;
301
302
/**
303
* Parse from file system path with encoding
304
* @param path Path to Java source file
305
* @param encoding Character encoding
306
* @return CompilationUnit representing the parsed code
307
* @throws IOException if file cannot be read
308
* @throws ParseProblemException if parsing fails
309
*/
310
public static CompilationUnit parse(Path path, Charset encoding) throws IOException;
311
```
312
313
**Usage Examples:**
314
315
```java
316
import java.nio.file.Paths;
317
import java.nio.charset.StandardCharsets;
318
319
// Parse from classpath
320
CompilationUnit cu1 = StaticJavaParser.parseResource("/com/example/Example.java");
321
322
// Parse from file system
323
Path sourcePath = Paths.get("src/main/java/Example.java");
324
CompilationUnit cu2 = StaticJavaParser.parse(sourcePath);
325
326
// Parse with specific encoding
327
CompilationUnit cu3 = StaticJavaParser.parse(sourcePath, StandardCharsets.UTF_8);
328
```
329
330
### Additional Parsing Methods
331
332
Parse other Java language constructs beyond the basic types.
333
334
```java { .api }
335
/**
336
* Parse an annotation expression
337
* @param annotation String containing annotation
338
* @return AnnotationExpr AST node
339
* @throws ParseProblemException if parsing fails
340
*/
341
public static AnnotationExpr parseAnnotation(String annotation);
342
343
/**
344
* Parse annotation body declaration (fields or methods)
345
* @param body String containing annotation body declaration
346
* @return BodyDeclaration AST node
347
* @throws ParseProblemException if parsing fails
348
*/
349
public static BodyDeclaration<?> parseAnnotationBodyDeclaration(String body);
350
351
/**
352
* Parse class or interface body declaration
353
* @param body String containing body declaration
354
* @return BodyDeclaration AST node
355
* @throws ParseProblemException if parsing fails
356
*/
357
public static BodyDeclaration<?> parseBodyDeclaration(String body);
358
359
/**
360
* Parse variable declaration expression
361
* @param declaration String containing variable declaration
362
* @return VariableDeclarationExpr AST node
363
* @throws ParseProblemException if parsing fails
364
*/
365
public static VariableDeclarationExpr parseVariableDeclarationExpr(String declaration);
366
367
/**
368
* Parse Javadoc content
369
* @param content String containing Javadoc content
370
* @return Javadoc AST node
371
* @throws ParseProblemException if parsing fails
372
*/
373
public static Javadoc parseJavadoc(String content);
374
375
/**
376
* Parse explicit constructor invocation (super/this calls)
377
* @param statement String containing constructor invocation
378
* @return ExplicitConstructorInvocationStmt AST node
379
* @throws ParseProblemException if parsing fails
380
*/
381
public static ExplicitConstructorInvocationStmt parseExplicitConstructorInvocationStmt(String statement);
382
383
/**
384
* Parse qualified name
385
* @param qualifiedName String containing qualified name
386
* @return Name AST node
387
* @throws ParseProblemException if parsing fails
388
*/
389
public static Name parseName(String qualifiedName);
390
391
/**
392
* Parse simple name
393
* @param name String containing simple name
394
* @return SimpleName AST node
395
* @throws ParseProblemException if parsing fails
396
*/
397
public static SimpleName parseSimpleName(String name);
398
399
/**
400
* Parse package declaration
401
* @param packageDeclaration String containing package declaration
402
* @return PackageDeclaration AST node
403
* @throws ParseProblemException if parsing fails
404
*/
405
public static PackageDeclaration parsePackageDeclaration(String packageDeclaration);
406
407
/**
408
* Parse module declaration (Java 9+)
409
* @param moduleDeclaration String containing module declaration
410
* @return ModuleDeclaration AST node
411
* @throws ParseProblemException if parsing fails
412
*/
413
public static ModuleDeclaration parseModuleDeclaration(String moduleDeclaration);
414
415
/**
416
* Parse module directive (Java 9+)
417
* @param moduleDirective String containing module directive
418
* @return ModuleDirective AST node
419
* @throws ParseProblemException if parsing fails
420
*/
421
public static ModuleDirective parseModuleDirective(String moduleDirective);
422
423
/**
424
* Parse type parameter
425
* @param typeParameter String containing type parameter
426
* @return TypeParameter AST node
427
* @throws ParseProblemException if parsing fails
428
*/
429
public static TypeParameter parseTypeParameter(String typeParameter);
430
431
/**
432
* Parse array initializer expression
433
* @param arrayInitializerExpr String containing array initializer
434
* @return ArrayInitializerExpr AST node
435
* @throws ParseProblemException if parsing fails
436
*/
437
public static ArrayInitializerExpr parseArrayInitializerExpr(String arrayInitializerExpr);
438
```
439
440
**Usage Examples:**
441
442
```java
443
// Parse annotations
444
AnnotationExpr annotation = StaticJavaParser.parseAnnotation("@Override");
445
AnnotationExpr paramAnnotation = StaticJavaParser.parseAnnotation("@NotNull(\"parameter cannot be null\")");
446
447
// Parse Javadoc
448
Javadoc javadoc = StaticJavaParser.parseJavadoc("This is a sample method\n@param x the input parameter\n@return the result");
449
450
// Parse module declarations
451
ModuleDeclaration module = StaticJavaParser.parseModuleDeclaration("module com.example { requires java.base; }");
452
453
// Parse type parameters
454
TypeParameter typeParam = StaticJavaParser.parseTypeParameter("T extends Comparable<T>");
455
456
// Parse variable declarations
457
VariableDeclarationExpr varDecl = StaticJavaParser.parseVariableDeclarationExpr("final String name = \"example\"");
458
```
459
460
## Error Handling Types
461
462
```java { .api }
463
/**
464
* Exception thrown when parsing fails
465
*/
466
public class ParseProblemException extends RuntimeException {
467
public List<Problem> getProblems();
468
}
469
470
/**
471
* Individual parsing problem
472
*/
473
public class Problem {
474
public String getMessage();
475
public Optional<TokenRange> getLocation();
476
public Problem.ProblemType getType();
477
478
public enum ProblemType {
479
ERROR, WARNING
480
}
481
}
482
```