1 /* 2 * Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 /** 27 * <h2>Provides classfile parsing, generation, and transformation library.</h2> 28 * The {@code java.lang.classfile} package contains classes for reading, writing, and 29 * modifying Java class files, as specified in Chapter {@jvms 4} of the 30 * <cite>Java Virtual Machine Specification</cite>. 31 * 32 * <h2>Reading classfiles</h2> 33 * The main class for reading classfiles is {@link java.lang.classfile.ClassModel}; we 34 * convert bytes into a {@link java.lang.classfile.ClassModel} with {@link 35 * java.lang.classfile.ClassFile#parse(byte[])}: 36 * 37 * {@snippet lang=java : 38 * ClassModel cm = ClassFile.of().parse(bytes); 39 * } 40 * 41 * There are several additional overloads of {@code parse} that let you specify 42 * various processing options. 43 * <p> 44 * A {@link java.lang.classfile.ClassModel} is an immutable description of a class 45 * file. It provides accessor methods to get at class metadata (e.g., {@link 46 * java.lang.classfile.ClassModel#thisClass()}, {@link java.lang.classfile.ClassModel#flags()}), 47 * as well as subordinate classfile entities ({@link java.lang.classfile.ClassModel#fields()}, 48 * {@link java.lang.classfile.ClassModel#attributes()}). A {@link 49 * java.lang.classfile.ClassModel} is inflated lazily; most parts of the classfile are 50 * not parsed until they are actually needed. 51 * <p> 52 * We can enumerate the names of the fields and methods in a class by: 53 * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods1"} 54 * <p> 55 * When we enumerate the methods, we get a {@link java.lang.classfile.MethodModel} for each method; like a 56 * {@code ClassModel}, it gives us access to method metadata and 57 * the ability to descend into subordinate entities such as the bytecodes of the 58 * method body. In this way, a {@code ClassModel} is the root of a 59 * tree, with children for fields, methods, and attributes, and {@code MethodModel} in 60 * turn has its own children (attributes, {@code CodeModel}, etc.) 61 * <p> 62 * Methods like {@link java.lang.classfile.ClassModel#methods} allows us to traverse the class structure 63 * explicitly, going straight to the parts we are interested in. This is useful 64 * for certain kinds of analysis, but if we wanted to process the whole 65 * classfile, we may want something more organized. A {@link 66 * java.lang.classfile.ClassModel} also provides us with a view of the classfile as a 67 * series of class <em>elements</em>, which may include methods, fields, attributes, 68 * and more, and which can be distinguished with pattern matching. We could 69 * rewrite the above example as: 70 * {@snippet lang="java" class="PackageSnippets" region="enumerateFieldsMethods2"} 71 * <p> 72 * The models returned as elements from traversing {@code ClassModel} can in 73 * turn be sources of elements. If we wanted to 74 * traverse a classfile and enumerate all the classes for which we access fields 75 * and methods, we can pick out the class elements that describe methods, then 76 * in turn pick out the method elements that describe the code attribute, and 77 * finally pick out the code elements that describe field access and invocation 78 * instructions: 79 * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies1"} 80 * <p> 81 * This same query could alternately be processed as a stream pipeline over 82 * class elements: 83 * {@snippet lang="java" class="PackageSnippets" region="gatherDependencies2"} 84 * 85 * <h3>Models and elements</h3> 86 * The view of classfiles presented by this API is framed in terms of 87 * <em>models</em> and <em>elements</em>. Models represent complex structures, 88 * such as classes, methods, fields, record elements, or the code body of a 89 * method. Models can be explored either via random-access navigation (such as 90 * the {@link java.lang.classfile.ClassModel#methods()} accessor) or as a linear 91 * sequence of <em>elements</em>. (Elements can in turn also be models; a {@link 92 * java.lang.classfile.FieldModel} is also an element of a class.) For each model type 93 * (e.g., {@link java.lang.classfile.MethodModel}), there is a corresponding element 94 * type ({@link java.lang.classfile.MethodElement}). Models and elements are immutable 95 * and are inflated lazily so creating a model does not necessarily require 96 * processing its entire content. 97 * 98 * <h3>The constant pool</h3> 99 * Much of the interesting content in a classfile lives in the <em>constant 100 * pool</em>. {@link java.lang.classfile.ClassModel} provides a lazily-inflated, 101 * read-only view of the constant pool via {@link java.lang.classfile.ClassModel#constantPool()}. 102 * Descriptions of classfile content is often exposed in the form of various 103 * subtypes of {@link java.lang.classfile.constantpool.PoolEntry}, such as {@link 104 * java.lang.classfile.constantpool.ClassEntry} or {@link java.lang.classfile.constantpool.Utf8Entry}. 105 * <p> 106 * Constant pool entries are also exposed through models and elements; in the 107 * above traversal example, the {@link java.lang.classfile.instruction.InvokeInstruction} 108 * element exposed a method for {@code owner} that corresponds to a {@code 109 * Constant_Class_info} entry in the constant pool. 110 * 111 * <h3>Attributes</h3> 112 * Much of the contents of a classfile is stored in attributes; attributes are 113 * found on classes, methods, fields, record components, and on the {@code Code} 114 * attribute. Most attributes are surfaced as elements; for example, {@link 115 * java.lang.classfile.attribute.SignatureAttribute} is a {@link 116 * java.lang.classfile.ClassElement}, {@link java.lang.classfile.MethodElement}, and {@link 117 * java.lang.classfile.FieldElement} since it can appear in all of those places, and is 118 * included when iterating the elements of the corresponding model. 119 * <p> 120 * Some attributes are not surfaced as elements; these are attributes that are 121 * tightly coupled to -- and logically part of -- other parts of the class file. 122 * These include the {@code BootstrapMethods}, {@code LineNumberTable}, {@code 123 * StackMapTable}, {@code LocalVariableTable}, and {@code 124 * LocalVariableTypeTable} attributes. These are processed by the library and 125 * treated as part of the structure they are coupled to (the entries of the 126 * {@code BootstrapMethods} attribute are treated as part of the constant pool; 127 * line numbers and local variable metadata are modeled as elements of {@link 128 * java.lang.classfile.CodeModel}.) 129 * <p> 130 * The {@code Code} attribute, in addition to being modeled as a {@link 131 * java.lang.classfile.MethodElement}, is also a model in its own right ({@link 132 * java.lang.classfile.CodeModel}) due to its complex structure. 133 * <p> 134 * Each standard attribute has an interface (in {@code java.lang.classfile.attribute}) 135 * which exposes the contents of the attribute and provides factories to 136 * construct the attribute. For example, the {@code Signature} attribute is 137 * defined by the {@link java.lang.classfile.attribute.SignatureAttribute} class, and 138 * provides accessors for {@link java.lang.classfile.attribute.SignatureAttribute#signature()} 139 * as well as factories taking {@link java.lang.classfile.constantpool.Utf8Entry} or 140 * {@link java.lang.String}. 141 * 142 * <h3>Custom attributes</h3> 143 * Attributes are converted between their classfile form and their corresponding 144 * object form via an {@link java.lang.classfile.AttributeMapper}. An {@code 145 * AttributeMapper} provides the 146 * {@link java.lang.classfile.AttributeMapper#readAttribute(AttributedElement, 147 * ClassReader, int)} method for mapping from the classfile format 148 * to an attribute instance, and the 149 * {@link java.lang.classfile.AttributeMapper#writeAttribute(java.lang.classfile.BufWriter, 150 * java.lang.classfile.Attribute)} method for mapping back to the classfile format. It also 151 * contains metadata including the attribute name, the set of classfile entities 152 * where the attribute is applicable, and whether multiple attributes of the 153 * same kind are allowed on a single entity. 154 * <p> 155 * There are built-in attribute mappers (in {@link java.lang.classfile.Attributes}) for 156 * each of the attribute types defined in section {@jvms 4.7} of <cite>The Java Virtual 157 * Machine Specification</cite>, as well as several common nonstandard attributes used by the 158 * JDK such as {@code CharacterRangeTable}. 159 * <p> 160 * Unrecognized attributes are delivered as elements of type {@link 161 * java.lang.classfile.attribute.UnknownAttribute}, which provide access only to the 162 * {@code byte[]} contents of the attribute. 163 * <p> 164 * For nonstandard attributes, user-provided attribute mappers can be specified 165 * through the use of the {@link 166 * java.lang.classfile.ClassFile.AttributeMapperOption#of(java.util.function.Function)}} 167 * classfile option. Implementations of custom attributes should extend {@link 168 * java.lang.classfile.CustomAttribute}. 169 * 170 * <h3>Options</h3> 171 * <p> 172 * {@link java.lang.classfile.ClassFile#of(java.lang.classfile.ClassFile.Option[])} 173 * accepts a list of options. {@link java.lang.classfile.ClassFile.Option} is a base interface 174 * for some statically enumerated options, as well as factories for more complex options, 175 * including: 176 * <ul> 177 * <li>{@link java.lang.classfile.ClassFile.AttributeMapperOption#of(java.util.function.Function)} 178 * -- specify format of custom attributes</li> 179 * <li>{@link java.lang.classfile.ClassFile.AttributesProcessingOption} 180 * -- unrecognized or problematic original attributes (default is {@code PASS_ALL_ATTRIBUTES})</li> 181 * <li>{@link java.lang.classfile.ClassFile.ClassHierarchyResolverOption#of(java.lang.classfile.ClassHierarchyResolver)} 182 * -- specify a custom class hierarchy resolver used by stack map generation</li> 183 * <li>{@link java.lang.classfile.ClassFile.ConstantPoolSharingOption}} 184 * -- share constant pool when transforming (default is {@code SHARED_POOL})</li> 185 * <li>{@link java.lang.classfile.ClassFile.DeadCodeOption}} 186 * -- patch out unreachable code (default is {@code PATCH_DEAD_CODE})</li> 187 * <li>{@link java.lang.classfile.ClassFile.DeadLabelsOption}} 188 * -- filter unresolved labels (default is {@code FAIL_ON_DEAD_LABELS})</li> 189 * <li>{@link java.lang.classfile.ClassFile.DebugElementsOption} 190 * -- processing of debug information, such as local variable metadata (default is {@code PASS_DEBUG}) </li> 191 * <li>{@link java.lang.classfile.ClassFile.LineNumbersOption} 192 * -- processing of line numbers (default is {@code PASS_LINE_NUMBERS}) </li> 193 * <li>{@link java.lang.classfile.ClassFile.ShortJumpsOption} 194 * -- automatically rewrite short jumps to long when necessary (default is {@code FIX_SHORT_JUMPS})</li> 195 * <li>{@link java.lang.classfile.ClassFile.StackMapsOption} 196 * -- generate stackmaps (default is {@code STACK_MAPS_WHEN_REQUIRED})</li> 197 * </ul> 198 * <p> 199 * Most options allow you to request that certain parts of the classfile be 200 * skipped during traversal, such as debug information or unrecognized 201 * attributes. Some options allow you to suppress generation of portions of the 202 * classfile, such as stack maps. Many of these options are to access 203 * performance tradeoffs; processing debug information and line numbers has a 204 * cost (both in writing and reading.) If you don't need this information, you 205 * can suppress it with options to gain some performance. 206 * 207 * <h2>Writing classfiles</h2> 208 * ClassFile generation is accomplished through <em>builders</em>. For each 209 * entity type that has a model, there is also a corresponding builder type; 210 * classes are built through {@link java.lang.classfile.ClassBuilder}, methods through 211 * {@link java.lang.classfile.MethodBuilder}, etc. 212 * <p> 213 * Rather than creating builders directly, builders are provided as an argument 214 * to a user-provided lambda. To generate the familiar "hello world" program, 215 * we ask for a class builder, and use that class builder to create method 216 * builders for the constructor and {@code main} method, and in turn use the 217 * method builders to create a {@code Code} attribute and use the code builders 218 * to generate the instructions: 219 * {@snippet lang="java" class="PackageSnippets" region="helloWorld1"} 220 * <p> 221 * The convenience methods {@code ClassBuilder.buildMethodBody} allows us to ask 222 * {@link ClassBuilder} to create code builders to build method bodies directly, 223 * skipping the method builder custom lambda: 224 * {@snippet lang="java" class="PackageSnippets" region="helloWorld2"} 225 * <p> 226 * Builders often support multiple ways of expressing the same entity at 227 * different levels of abstraction. For example, the {@code invokevirtual} 228 * instruction invoking {@code println} could have been generated with {@link 229 * java.lang.classfile.CodeBuilder#invokevirtual(java.lang.constant.ClassDesc, 230 * java.lang.String, java.lang.constant.MethodTypeDesc) CodeBuilder.invokevirtual}, {@link 231 * java.lang.classfile.CodeBuilder#invoke(java.lang.classfile.Opcode, 232 * java.lang.constant.ClassDesc, java.lang.String, java.lang.constant.MethodTypeDesc, 233 * boolean) CodeBuilder.invokeInstruction}, or {@link 234 * java.lang.classfile.CodeBuilder#with(java.lang.classfile.ClassFileElement) 235 * CodeBuilder.with}. 236 * <p> 237 * The convenience method {@code CodeBuilder.invokevirtual} behaves as if it calls 238 * the convenience method {@code CodeBuilder.invokeInstruction}, which in turn behaves 239 * as if it calls method {@code CodeBuilder.with}. This composing of method calls on the 240 * builder enables the composing of transforms (as described later). 241 * <p> 242 * Unless otherwise noted, passing a {@code null} argument to a constructor 243 * or method of any Class-File API class or interface will cause a {@link 244 * java.lang.NullPointerException NullPointerException} to be thrown. Additionally, 245 * invoking a method with an array or collection containing a {@code null} element 246 * will cause a {@code NullPointerException}, unless otherwise specified. </p> 247 * 248 * <h3>Symbolic information</h3> 249 * To describe symbolic information for classes and types, the API uses the 250 * nominal descriptor abstractions from {@code java.lang.constant} such as {@link 251 * java.lang.constant.ClassDesc} and {@link java.lang.constant.MethodTypeDesc}, 252 * which is less error-prone than using raw strings. 253 * <p> 254 * If a constant pool entry has a nominal representation then it provides a 255 * method returning the corresponding nominal descriptor type e.g. 256 * method {@link java.lang.classfile.constantpool.ClassEntry#asSymbol} returns 257 * {@code ClassDesc}. 258 * <p> 259 * Where appropriate builders provide two methods for building an element with 260 * symbolic information, one accepting nominal descriptors, and the other 261 * accepting constant pool entries. 262 * 263 * <h3>Consistency checks, syntax checks and verification</h3> 264 * No consistency checks are performed while building or transforming classfiles 265 * (except for null arguments checks). All builders and classfile elements factory 266 * methods accepts the provided information without implicit validation. 267 * However, fatal inconsistencies (like for example invalid code sequence or 268 * unresolved labels) affects internal tools and may cause exceptions later in 269 * the classfile building process. 270 * <p> 271 * Using nominal descriptors assures the right serial form is applied by the 272 * ClassFile API library based on the actual context. Also these nominal 273 * descriptors are validated during their construction, so it is not possible to 274 * create them with invalid content by mistake. Following example pass class 275 * name to the {@link java.lang.constant.ClassDesc#of} method for validation 276 * and the library performs automatic conversion to the right internal form of 277 * the class name when serialized in the constant pool as a class entry. 278 * {@snippet lang=java : 279 * var validClassEntry = constantPoolBuilder.classEntry(ClassDesc.of("mypackage.MyClass")); 280 * } 281 * <p> 282 * On the other hand it is possible to use builders methods and factories accepting 283 * constant pool entries directly. Constant pool entries can be constructed also 284 * directly from raw values, with no additional conversions or validations. 285 * Following example uses intentionally wrong class name form and it is applied 286 * without any validation or conversion. 287 * {@snippet lang=java : 288 * var invalidClassEntry = constantPoolBuilder.classEntry( 289 * constantPoolBuilder.utf8Entry("mypackage.MyClass")); 290 * } 291 * <p> 292 * More complex verification of a classfile can be achieved by invocation of 293 * {@link java.lang.classfile.ClassFile#verify}. 294 * 295 * <h2>Transforming classfiles</h2> 296 * ClassFile Processing APIs are most frequently used to combine reading and 297 * writing into transformation, where a classfile is read, localized changes are 298 * made, but much of the classfile is passed through unchanged. For each kind 299 * of builder, {@code XxxBuilder} has a method {@code with(XxxElement)} so that 300 * elements that we wish to pass through unchanged can be handed directly back 301 * to the builder. 302 * <p> 303 * If we wanted to strip out methods whose names starts with "debug", we could 304 * get an existing {@link java.lang.classfile.ClassModel}, build a new classfile that 305 * provides a {@link java.lang.classfile.ClassBuilder}, iterate the elements of the 306 * original {@link java.lang.classfile.ClassModel}, and pass through all of them to 307 * the builder except the methods we want to drop: 308 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods1"} 309 * <p> 310 * This hands every class element, except for those corresponding to methods 311 * whose names start with {@code debug}, back to the builder. Transformations 312 * can of course be more complicated, diving into method bodies and instructions 313 * and transforming those as well, but the same structure is repeated at every 314 * level, since every entity has corresponding model, builder, and element 315 * abstractions. 316 * <p> 317 * Transformation can be viewed as a "flatMap" operation on the sequence of 318 * elements; for every element, we could pass it through unchanged, drop it, or 319 * replace it with one or more elements. Because transformation is such a 320 * common operation on classfiles, each model type has a corresponding {@code 321 * XxxTransform} type (which describes a transform on a sequence of {@code 322 * XxxElement}) and each builder type has {@code transformYyy} methods for transforming 323 * its child models. A transform is simply a functional interface that takes a 324 * builder and an element, and an implementation "flatMap"s elements 325 * into the builder. We could express the above as: 326 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods2"} 327 * <p> 328 * {@code ClassTransform.dropping} convenience method allow us to simplify the same 329 * transformation construction and express the above as: 330 * {@snippet lang="java" class="PackageSnippets" region="stripDebugMethods3"} 331 * 332 * <h3>Lifting transforms</h3> 333 * While the example using transformations are only slightly shorter, the 334 * advantage of expressing transformation in this way is that the transform 335 * operations can be more easily combined. Suppose we want to redirect 336 * invocations of static methods on {@code Foo} to the corresponding method on 337 * {@code Bar} instead. We could express this as a transformation on {@link 338 * java.lang.classfile.CodeElement}: 339 * {@snippet lang="java" class="PackageSnippets" region="fooToBarTransform"} 340 * <p> 341 * We can then <em>lift</em> this transformation on code elements into a 342 * transformation on method elements. This intercepts method elements that 343 * correspond to a {@code Code} attribute, dives into its code elements, and 344 * applies the code transform to them, and passes other method elements through 345 * unchanged: 346 * {@snippet lang=java : 347 * MethodTransform mt = MethodTransform.transformingCode(fooToBar); 348 * } 349 * <p> 350 * and further lift the transform on method elements into one on class 351 * elements: 352 * {@snippet lang=java : 353 * ClassTransform ct = ClassTransform.transformingMethods(mt); 354 * } 355 * <p> 356 * or lift the code transform into the class transform directly: 357 * {@snippet lang=java : 358 * ClassTransform ct = ClassTransform.transformingMethodBodiess(fooToBar); 359 * } 360 * <p> 361 * and then transform the classfile: 362 * {@snippet lang=java : 363 * var cc = ClassFile.of(); 364 * byte[] newBytes = cc.transform(cc.parse(bytes), ct); 365 * } 366 * <p> 367 * This is much more concise (and less error-prone) than the equivalent 368 * expressed by traversing the classfile structure directly: 369 * {@snippet lang="java" class="PackageSnippets" region="fooToBarUnrolled"} 370 * 371 * <h3>Composing transforms</h3> 372 * Transforms on the same type of element can be composed in sequence, where the 373 * output of the first is fed to the input of the second. Suppose we want to 374 * instrument all method calls, where we print the name of a method before 375 * calling it: 376 * {@snippet lang="java" class="PackageSnippets" region="instrumentCallsTransform"} 377 * <p> 378 * Then we can compose {@code fooToBar} and {@code instrumentCalls} with {@link 379 * java.lang.classfile.CodeTransform#andThen(java.lang.classfile.CodeTransform)}: 380 * 381 * {@snippet lang=java : 382 * var cc = ClassFile.of(); 383 * byte[] newBytes = cc.transform(cc.parse(bytes), 384 * ClassTransform.transformingMethods( 385 * MethodTransform.transformingCode( 386 * fooToBar.andThen(instrumentCalls)))); 387 * } 388 * 389 * Transform {@code instrumentCalls} will receive all code elements produced by 390 * transform {@code forToBar}, either those code elements from the original classfile 391 * or replacements (replacing static invocations to {@code Foo} with those to {@code Bar}). 392 * 393 * <h3>Constant pool sharing</h3> 394 * Transformation doesn't merely handle the logistics of reading, transforming 395 * elements, and writing. Most of the time when we are transforming a 396 * classfile, we are making relatively minor changes. To optimize such cases, 397 * transformation seeds the new classfile with a copy of the constant pool from 398 * the original classfile; this enables significant optimizations (methods and 399 * attributes that are not transformed can be processed by bulk-copying their 400 * bytes, rather than parsing them and regenerating their contents.) If 401 * constant pool sharing is not desired it can be suppressed 402 * with the {@link java.lang.classfile.ClassFile.ConstantPoolSharingOption} option. 403 * Such suppression may be beneficial when transformation removes many elements, 404 * resulting in many unreferenced constant pool entries. 405 * 406 * <h3>Transformation handling of unknown classfile elements</h3> 407 * Custom classfile transformations might be unaware of classfile elements 408 * introduced by future JDK releases. To achieve deterministic stability, 409 * classfile transforms interested in consuming all classfile elements should be 410 * implemented strictly to throw exceptions if running on a newer JDK, if the 411 * transformed class file is a newer version, or if a new and unknown classfile 412 * element appears. As for example in the following strict compatibility-checking 413 * transformation snippets: 414 * {@snippet lang="java" class="PackageSnippets" region="strictTransform1"} 415 * {@snippet lang="java" class="PackageSnippets" region="strictTransform2"} 416 * {@snippet lang="java" class="PackageSnippets" region="strictTransform3"} 417 * <p> 418 * Conversely, classfile transforms that are only interested in consuming a portion 419 * of classfile elements do not need to concern with new and unknown classfile 420 * elements and may pass them through. Following example shows such future-proof 421 * code transformation: 422 * {@snippet lang="java" class="PackageSnippets" region="benevolentTransform"} 423 * 424 * <h2>API conventions</h2> 425 * <p> 426 * The API is largely derived from a <a href="#data_model"><em>data model</em></a> 427 * for the classfile format, which defines each element kind (which includes models and 428 * attributes) and its properties. For each element kind, there is a 429 * corresponding interface to describe that element, and factory methods to 430 * create that element. Some element kinds also have convenience methods on the 431 * corresponding builder (e.g., {@link 432 * java.lang.classfile.CodeBuilder#invokevirtual(java.lang.constant.ClassDesc, 433 * java.lang.String, java.lang.constant.MethodTypeDesc)}). 434 * <p> 435 * Most symbolic information in elements is represented by constant pool entries 436 * (for example, the owner of a field is represented by a {@link 437 * java.lang.classfile.constantpool.ClassEntry}.) Factories and builders also 438 * accept nominal descriptors from {@code java.lang.constant} (e.g., {@link 439 * java.lang.constant.ClassDesc}.) 440 * 441 * <h2><a id="data_model"></a>Data model</h2> 442 * We define each kind of element by its name, an optional arity indicator (zero 443 * or more, zero or one, exactly one), and a list of components. The elements 444 * of a class are fields, methods, and the attributes that can appear on 445 * classes: 446 * 447 * {@snippet lang="text" : 448 * ClassElement = 449 * FieldModel*(UtfEntry name, Utf8Entry descriptor) 450 * | MethodModel*(UtfEntry name, Utf8Entry descriptor) 451 * | ModuleAttribute?(int flags, ModuleEntry moduleName, UtfEntry moduleVersion, 452 * List<ModuleRequireInfo> requires, List<ModuleOpenInfo> opens, 453 * List<ModuleExportInfo> exports, List<ModuleProvidesInfo> provides, 454 * List<ClassEntry> uses) 455 * | ModulePackagesAttribute?(List<PackageEntry> packages) 456 * | ModuleTargetAttribute?(Utf8Entry targetPlatform) 457 * | ModuleHashesAttribute?(Utf8Entry algorithm, List<HashInfo> hashes) 458 * | ModuleResolutionAttribute?(int resolutionFlags) 459 * | SourceFileAttribute?(Utf8Entry sourceFile) 460 * | SourceDebugExtensionsAttribute?(byte[] contents) 461 * | CompilationIDAttribute?(Utf8Entry compilationId) 462 * | SourceIDAttribute?(Utf8Entry sourceId) 463 * | NestHostAttribute?(ClassEntry nestHost) 464 * | NestMembersAttribute?(List<ClassEntry> nestMembers) 465 * | RecordAttribute?(List<RecordComponent> components) 466 * | EnclosingMethodAttribute?(ClassEntry className, NameAndTypeEntry method) 467 * | InnerClassesAttribute?(List<InnerClassInfo> classes) 468 * | PermittedSubclassesAttribute?(List<ClassEntry> permittedSubclasses) 469 * | LoadableDescriptorsAttribute?(List<Utf8Entry> loadableDescriptors) 470 * | DeclarationElement* 471 * } 472 * 473 * where {@code DeclarationElement} are the elements that are common to all declarations 474 * (classes, methods, fields) and so are factored out: 475 * 476 * {@snippet lang="text" : 477 * DeclarationElement = 478 * SignatureAttribute?(Utf8Entry signature) 479 * | SyntheticAttribute?() 480 * | DeprecatedAttribute?() 481 * | RuntimeInvisibleAnnotationsAttribute?(List<Annotation> annotations) 482 * | RuntimeVisibleAnnotationsAttribute?(List<Annotation> annotations) 483 * | CustomAttribute* 484 * | UnknownAttribute* 485 * } 486 * 487 * Fields and methods are models with their own elements. The elements of fields 488 * and methods are fairly simple; most of the complexity of methods lives in the 489 * {@link java.lang.classfile.CodeModel} (which models the {@code Code} attribute 490 * along with the code-related attributes: stack map table, local variable table, 491 * line number table, etc.) 492 * 493 * {@snippet lang="text" : 494 * FieldElement = 495 * DeclarationElement 496 * | ConstantValueAttribute?(ConstantValueEntry constant) 497 * 498 * MethodElement = 499 * DeclarationElement 500 * | CodeModel?() 501 * | AnnotationDefaultAttribute?(ElementValue defaultValue) 502 * | MethodParametersAttribute?(List<MethodParameterInfo> parameters) 503 * | ExceptionsAttribute?(List<ClassEntry> exceptions) 504 * } 505 * 506 * {@link java.lang.classfile.CodeModel} is unique in that its elements are <em>ordered</em>. 507 * Elements of {@code Code} include ordinary bytecodes, as well as a number of pseudo-instructions 508 * representing branch targets, line number metadata, local variable metadata, and 509 * catch blocks. 510 * 511 * {@snippet lang="text" : 512 * CodeElement = Instruction | PseudoInstruction 513 * 514 * Instruction = 515 * LoadInstruction(TypeKind type, int slot) 516 * | StoreInstruction(TypeKind type, int slot) 517 * | IncrementInstruction(int slot, int constant) 518 * | BranchInstruction(Opcode opcode, Label target) 519 * | LookupSwitchInstruction(Label defaultTarget, List<SwitchCase> cases) 520 * | TableSwitchInstruction(Label defaultTarget, int low, int high, 521 * List<SwitchCase> cases) 522 * | ReturnInstruction(TypeKind kind) 523 * | ThrowInstruction() 524 * | FieldInstruction(Opcode opcode, FieldRefEntry field) 525 * | InvokeInstruction(Opcode opcode, MemberRefEntry method, boolean isInterface) 526 * | InvokeDynamicInstruction(InvokeDynamicEntry invokedynamic) 527 * | NewObjectInstruction(ClassEntry className) 528 * | NewReferenceArrayInstruction(ClassEntry componentType) 529 * | NewPrimitiveArrayInstruction(TypeKind typeKind) 530 * | NewMultiArrayInstruction(ClassEntry componentType, int dims) 531 * | ArrayLoadInstruction(Opcode opcode) 532 * | ArrayStoreInstruction(Opcode opcode) 533 * | TypeCheckInstruction(Opcode opcode, ClassEntry className) 534 * | ConvertInstruction(TypeKind from, TypeKind to) 535 * | OperatorInstruction(Opcode opcode) 536 * | ConstantInstruction(ConstantDesc constant) 537 * | StackInstruction(Opcode opcode) 538 * | MonitorInstruction(Opcode opcode) 539 * | NopInstruction() 540 * 541 * PseudoInstruction = 542 * | LabelTarget(Label label) 543 * | LineNumber(int line) 544 * | ExceptionCatch(Label tryStart, Label tryEnd, Label handler, ClassEntry exception) 545 * | LocalVariable(int slot, UtfEntry name, Utf8Entry type, Label startScope, Label endScope) 546 * | LocalVariableType(int slot, Utf8Entry name, Utf8Entry type, Label startScope, Label endScope) 547 * | CharacterRange(int rangeStart, int rangeEnd, int flags, Label startScope, Label endScope) 548 * } 549 * 550 * @since 22 551 */ 552 @PreviewFeature(feature = PreviewFeature.Feature.CLASSFILE_API) 553 package java.lang.classfile; 554 555 import jdk.internal.javac.PreviewFeature;