or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ast-navigation.mdconfiguration.mdindex.mdparsing.mdprinting.mdserialization.mdsymbol-resolution.mdvisitors.md

index.mddocs/

0

# JavaParser Core

1

2

JavaParser Core is a comprehensive Java parsing library that provides complete support for parsing Java source code from Java 1.0 through Java 21. It offers advanced analysis functionalities including AST generation, symbol resolution, type solving, and code transformation utilities, making it essential for code analysis tools, IDEs, static analysis frameworks, and code generation systems.

3

4

## Package Information

5

6

- **Package Name**: javaparser-core

7

- **Package Type**: maven

8

- **Group ID**: com.github.javaparser

9

- **Language**: Java

10

- **Installation**:

11

```xml

12

<dependency>

13

<groupId>com.github.javaparser</groupId>

14

<artifactId>javaparser-core</artifactId>

15

<version>3.27.0</version>

16

</dependency>

17

```

18

19

## Core Imports

20

21

```java

22

import com.github.javaparser.StaticJavaParser;

23

import com.github.javaparser.ast.CompilationUnit;

24

import com.github.javaparser.ast.Node;

25

import com.github.javaparser.ast.visitor.VoidVisitor;

26

import com.github.javaparser.ast.visitor.GenericVisitor;

27

```

28

29

## Basic Usage

30

31

```java

32

import com.github.javaparser.StaticJavaParser;

33

import com.github.javaparser.ast.CompilationUnit;

34

import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;

35

36

// Parse Java source code

37

String code = """

38

public class Example {

39

public void hello() {

40

System.out.println("Hello World");

41

}

42

}

43

""";

44

45

CompilationUnit cu = StaticJavaParser.parse(code);

46

47

// Find all class declarations

48

List<ClassOrInterfaceDeclaration> classes = cu.findAll(ClassOrInterfaceDeclaration.class);

49

for (ClassOrInterfaceDeclaration cls : classes) {

50

System.out.println("Found class: " + cls.getNameAsString());

51

}

52

53

// Use visitor pattern to analyze AST

54

cu.accept(new VoidVisitorAdapter<Void>() {

55

@Override

56

public void visit(MethodDeclaration n, Void arg) {

57

System.out.println("Method: " + n.getNameAsString());

58

super.visit(n, arg);

59

}

60

}, null);

61

```

62

63

## Architecture

64

65

JavaParser Core is built around several key components:

66

67

- **Parsing Engine**: High-performance parser built with JavaCC supporting all Java language versions

68

- **AST Model**: Complete Abstract Syntax Tree representation with over 100 node types

69

- **Visitor Pattern**: Flexible traversal and analysis through GenericVisitor and VoidVisitor interfaces

70

- **Symbol Resolution**: Advanced type analysis and symbol resolution capabilities

71

- **Code Generation**: Pretty printing and various output formats (Java, XML, DOT)

72

- **Configuration System**: Comprehensive parser configuration for language levels and behavior

73

- **Metamodel**: Reflection-like API for introspecting AST structure

74

75

## Capabilities

76

77

### Core Parsing

78

79

The fundamental parsing functionality for converting Java source code into Abstract Syntax Trees. Supports all Java language constructs from Java 1.0 through Java 21.

80

81

```java { .api }

82

// Simple static parsing methods

83

public static CompilationUnit parse(String code);

84

public static CompilationUnit parse(File file) throws FileNotFoundException;

85

public static CompilationUnit parse(InputStream in);

86

87

// Expression parsing

88

public static <T extends Expression> T parseExpression(String expression);

89

public static Statement parseStatement(String statement);

90

public static Type parseType(String type);

91

```

92

93

[Core Parsing](./parsing.md)

94

95

### AST Navigation and Manipulation

96

97

Complete Abstract Syntax Tree model with navigation, search, and modification capabilities. All AST nodes extend the base Node class with common functionality.

98

99

```java { .api }

100

// Base Node functionality

101

public abstract class Node {

102

public <R, A> R accept(GenericVisitor<R, A> v, A arg);

103

public <A> void accept(VoidVisitor<A> v, A arg);

104

public <T> List<T> findAll(Class<T> clazz);

105

public Optional<Node> getParentNode();

106

public boolean replace(Node node);

107

public boolean remove();

108

public Node clone();

109

}

110

111

// Root compilation unit

112

public class CompilationUnit extends Node {

113

public NodeList<TypeDeclaration<?>> getTypes();

114

public NodeList<ImportDeclaration> getImports();

115

public Optional<PackageDeclaration> getPackageDeclaration();

116

}

117

```

118

119

[AST Navigation](./ast-navigation.md)

120

121

### Visitor Pattern

122

123

Flexible traversal and analysis of AST nodes using the visitor pattern. Supports both generic visitors that return values and void visitors for side effects.

124

125

```java { .api }

126

public interface GenericVisitor<R, A> {

127

R visit(CompilationUnit n, A arg);

128

R visit(ClassOrInterfaceDeclaration n, A arg);

129

R visit(MethodDeclaration n, A arg);

130

// ... visit methods for all AST node types

131

}

132

133

public interface VoidVisitor<A> {

134

void visit(CompilationUnit n, A arg);

135

void visit(ClassOrInterfaceDeclaration n, A arg);

136

void visit(MethodDeclaration n, A arg);

137

// ... visit methods for all AST node types

138

}

139

```

140

141

[Visitor Pattern](./visitors.md)

142

143

### Code Generation and Printing

144

145

Convert AST nodes back to formatted Java source code, XML representation, or graph visualization formats.

146

147

```java { .api }

148

public class PrettyPrinter implements ConfigurablePrinter {

149

public String print(Node node);

150

}

151

152

public class XmlPrinter {

153

public String print(Node node);

154

}

155

156

public class DotPrinter {

157

public String print(Node node);

158

}

159

```

160

161

[Code Generation](./printing.md)

162

163

### Symbol Resolution and Type Analysis

164

165

Advanced symbol resolution for resolving references to their declarations and performing type analysis.

166

167

```java { .api }

168

public interface SymbolResolver {

169

<T> T resolveDeclaration(Node node, Class<T> resultClass);

170

}

171

172

public interface TypeSolver {

173

SymbolReference<ResolvedReferenceTypeDeclaration> tryToSolveType(String name);

174

}

175

176

public class ParserConfiguration {

177

public ParserConfiguration setSymbolResolver(SymbolResolver symbolResolver);

178

}

179

```

180

181

[Symbol Resolution](./symbol-resolution.md)

182

183

### Parser Configuration

184

185

Comprehensive configuration system for controlling parsing behavior, language level support, and feature enabling.

186

187

```java { .api }

188

public class ParserConfiguration {

189

public ParserConfiguration setLanguageLevel(LanguageLevel languageLevel);

190

public ParserConfiguration setCharacterEncoding(Charset characterEncoding);

191

public ParserConfiguration setStoreTokens(boolean storeTokens);

192

public ParserConfiguration setSymbolResolver(SymbolResolver symbolResolver);

193

194

public enum LanguageLevel {

195

JAVA_1_0, JAVA_1_1, JAVA_1_2, JAVA_1_3, JAVA_1_4,

196

JAVA_5, JAVA_6, JAVA_7, JAVA_8, JAVA_9, JAVA_10,

197

JAVA_11, JAVA_12, JAVA_13, JAVA_14, JAVA_15, JAVA_16,

198

JAVA_17, JAVA_18, JAVA_19, JAVA_20, JAVA_21, CURRENT

199

}

200

}

201

```

202

203

[Parser Configuration](./configuration.md)

204

205

### AST Serialization

206

207

Convert AST nodes to and from JSON format for storage, transmission, and persistence. Enables distributed processing and analysis pipelines.

208

209

```java { .api }

210

public class JavaParserJsonSerializer {

211

public String serialize(Node node);

212

public void serialize(Node node, OutputStream out) throws IOException;

213

}

214

215

public class JavaParserJsonDeserializer {

216

public Node deserialize(String json) throws JsonProcessingException;

217

public <T extends Node> T deserialize(String json, Class<T> nodeType) throws JsonProcessingException;

218

}

219

```

220

221

[AST Serialization](./serialization.md)

222

223

## Common Types

224

225

```java { .api }

226

// Parse result with error handling

227

public class ParseResult<T> {

228

public Optional<T> getResult();

229

public List<Problem> getProblems();

230

public boolean isSuccessful();

231

}

232

233

// Position and range information

234

public class Position {

235

public int line;

236

public int column;

237

public Position(int line, int column);

238

}

239

240

public class Range {

241

public Position begin;

242

public Position end;

243

public Range(Position begin, Position end);

244

}

245

246

// Observable list for AST nodes

247

public class NodeList<T> extends ArrayList<T> implements Observable {

248

// Standard List interface plus observable functionality

249

}

250

251

// Data key for attaching metadata to nodes

252

public abstract class DataKey<T> {

253

public static <T> DataKey<T> create();

254

}

255

256

// Token range information

257

public class TokenRange {

258

public JavaToken getBegin();

259

public JavaToken getEnd();

260

}

261

262

// Java token information

263

public class JavaToken {

264

public int getKind();

265

public String getText();

266

public Optional<Range> getRange();

267

}

268

269

// Tree traversal strategies

270

public enum TreeTraversal {

271

PREORDER, POSTORDER, BREADTHFIRST, PARENTS, DIRECT_CHILDREN

272

}

273

274

// Modifier keywords

275

public enum Modifier.Keyword {

276

PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, ABSTRACT, SYNCHRONIZED,

277

NATIVE, STRICTFP, TRANSIENT, VOLATILE, DEFAULT, SEALED, NON_SEALED

278

}

279

```