Zero-invasive compile-time type conversion generation method
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2026-01-19
- Publication Date
- 2026-08-11
AI Technical Summary
1、泛型类型安全性不足:由于Java泛型的类型擦除机制,运行时容易出现‘ClassCastException’;
[0016]本公开实施例以零侵入方式在源代码中声明类型转换意图与安全策略,使注解处理器(APT)在编译期能够在不改动业务逻辑的前提下,自动生成类型安全的转换器类代码,并将尽可能多的校验提前到编译期(语法与语义级),以便在编译期给出明确定位与修复建议。进一步地,本公开实施例通过源类型描述符和目标类型描述符决定源类型和目标类型之间的转换方法,并据此构建转换器类代码以实现安全的类型转换。
Smart Images

Figure CN121979502B_ABST
Abstract
Description
Technical Field
[0001] This disclosure relates to the field of computer technology, and in particular to a compile-time type conversion generation method oriented towards zero intrusion. Background Technology
[0002] Java has a compiler and a virtual machine. The compiler converts Java source code into bytecode (.class files), and the virtual machine loads and runs the bytecode. Various type conversions are defined in the Java source code, and these conversions are usually verified by the compiler. However, there are some conversions that, although verified by the compiler, can be detected by the virtual machine as type incompatibility and a runtime exception 'classCastException' will be thrown. This exception can arise from the following: 1. Insufficient type safety of generics: Due to Java's type erasure mechanism, 'ClassCastException' is prone to occur at runtime; 2. Limitations of dynamic conversion: Although object and byte stream conversion is achieved through type casting, it still relies on runtime parsing and lacks compile-time guarantees.
[0003] 3. Limitations of using annotation processors (APT): Although it involves using APT to generate transformation logic, it only handles limited scenarios such as null values, lacks deep support for complex structures, and does not combine with security enhancement mechanisms (such as immutable set generation and strong type assertions).
[0004] Therefore, an improved solution is needed that can eliminate type conversion insecurity at compile time, automatically generate deep conversion logic, and enhance runtime safety. Summary of the Invention
[0005] The purpose of this disclosure is to provide a zero-intrusion compile-time type conversion generation method to solve the problems existing in the prior art.
[0006] According to a first aspect of the present disclosure, a compile-time type conversion generation method oriented towards zero intrusion is provided, comprising: Scan and parse type conversion annotations in the source code, and build generation tasks for the type conversion annotations, the generation tasks indicating the annotated element information and the target type expression; For each generation task, a source type descriptor is constructed for the annotated element, and a target type descriptor is constructed for the target type expression, wherein the source type descriptor and the target type descriptor are based on the same data model; Perform a consistency check on the source type descriptor and the target type descriptor in each generation task; A generation task is provided for the consistency check determination to perform safe conversion, generating type-safe converter class code. The converter class code embeds security enhancement logic based on type conversion annotations. When the converter class code is called, safe type conversion is implemented.
[0007] In some embodiments, constructing a source type descriptor for the annotated element includes: The compiler-provided type information is used to obtain the primitive type and parameter information of the annotated element as specified by the compiler, and then the primitive type and parameter group in the source type descriptor are updated accordingly. Constructing a target type descriptor for the target type expression includes: Perform lexical or syntactic analysis on the target type expression and generate a syntax tree; and The syntax tree is mapped to the target type descriptor based on the parsing context, and the values of the primitive type and parameter group in the target type descriptor are derived from the target type expression.
[0008] In some embodiments, the consistency check includes checking whether the original types in the source type descriptor and the target type descriptor are compatible and whether the lengths of the parameter groups are consistent.
[0009] In some embodiments, the generation of type-safe converter class code includes: A bottom-up traversal is performed on the matching nodes of the target type descriptor and the source type descriptor to determine whether a matching node requires an auxiliary conversion method, and a private auxiliary conversion method is generated accordingly; and Generate a top-level public conversion method, which internally calls the private auxiliary conversion method and integrates security enhancement logic based on the type conversion annotation.
[0010] In some embodiments, when generating a private auxiliary transformation method, a placeholder implementation is generated for the detected circular dependency type, and then replaced with the full implementation in subsequent processing rounds.
[0011] In some embodiments, the security enhancement logic includes one or more of the following: null value policy handling, type assertion, exception handling, immutable collection wrapping, and conversion report marking.
[0012] In some embodiments, the method further includes generating a manifest file at compile time, the manifest file including a task identifier, a generated converter class name, a type key, version information, and a signature.
[0013] In some embodiments, the method further includes: invoking the converter class code in one of the following ways: The business logic code directly calls the generated converter class statically; The converter is dynamically searched and invoked based on the type key in the runtime registry; The generated converter is registered to the application framework's conversion service via the framework adapter.
[0014] According to a second aspect of the present disclosure, a computing device is provided, including a memory and a processor, wherein the memory stores a computer program, characterized in that the processor, when executing the computer program, implements the steps of the compile-time type conversion generation method described above.
[0015] According to a third aspect of the present disclosure, a computer-readable storage medium is provided, on which a computer program is stored, wherein when the computer program is executed by a processor, it implements the steps of the compile-time type conversion generation method described above.
[0016] This disclosure declares type conversion intent and security strategies in the source code in a zero-intrusion manner, enabling the annotation processor (APT) to automatically generate type-safe converter class code at compile time without modifying the business logic. It also advances as much verification as possible to compile time (syntax and semantic level) to provide clear location and repair suggestions during compilation. Furthermore, this disclosure determines the conversion method between the source and target types through source and target type descriptors, and constructs converter class code accordingly to achieve safe type conversion. Attached Figure Description
[0017] The above and other objects, features and advantages of the present disclosure will become more apparent from the following description of embodiments of the present disclosure with reference to the accompanying drawings, in which: Figure 1 This is a flowchart of the compile-time type conversion generation method provided in this embodiment of the disclosure; Figure 2 A workflow for compiling and executing computer programs implemented based on embodiments of this disclosure is provided. Detailed Implementation
[0018] Embodiments of the present disclosure will now be described in more detail with reference to the accompanying drawings. In the various drawings, the same elements are indicated by similar reference numerals. For clarity, the various parts in the drawings are not drawn to scale. Furthermore, certain well-known parts may not be shown.
[0019] The following description of embodiments of the present disclosure is based on examples, but the embodiments of the present disclosure are not limited to these embodiments. In the detailed description of the embodiments of the present disclosure below, certain specific details are described in detail. Those skilled in the art can fully understand the embodiments of the present disclosure without these details. To avoid obscuring the essence of the embodiments of the present disclosure, well-known methods, processes, flows, elements, and circuits are not described in detail.
[0020] Unless the context explicitly requires it, the terms "comprising," "including," and similar terms throughout the specification and claims should be interpreted as encompassing rather than exclusive or exhaustive; that is, meaning "including but not limited to." Furthermore, in the description of embodiments of this disclosure, unless otherwise stated, "a plurality of" means two or more.
[0021] Terminology Explanation
[0022] Annotation Processing Tool (APT) is a tool provided by JAVAC that scans and processes annotations during compilation. It detects annotations in source code files and then performs additional processing based on those annotations.
[0023] Figure 1 This is a flowchart of a compile-time type conversion generation method provided in this embodiment. This method can be implemented as a specific embodiment of an existing annotation processor (APT). Figure 1 As shown, this method includes the following steps.
[0024] In step S01, type conversion annotations in the source code are scanned and parsed, and a generation task is built for the type conversion annotations.
[0025] Type conversion annotations are applied to annotated elements to indicate the intent to convert from the "source type" in the annotated element to the "target type" indicated by the target type expression. Annotated elements can be variable definitions, method return values, method parameters, class declarations, etc., and the target type expression can be a string composed of wildcards, numbers, characters, etc.
[0026] Type conversion annotations can also include safety policies and custom converters. Safety policies indicate the validation strategies required for type conversions, such as null policy, immutable flag, and strict mode. When null policy is set to 'true', it indicates the code behavior should be specified when encountering 'null'. When immutable flag is set to 'true', it indicates that the generated code should immutably wrap the output set. When strict mode is set to 'true', type mismatches will be treated as errors at compile time / runtime. Custom converters are APIs that developers explicitly specify to be used when annotated elements are converted.
[0027] The annotation processor can verify the syntactic integrity (angle brackets / commas / wildcards / array symbols) of each type conversion annotation and build a generation task for the type conversion annotations that pass the verification. The generation task may include information obtained from the type conversion annotation (e.g., the identifier of the annotated element and the target type expression), source code context information (e.g., generic context), and some information obtained from the compiler currently executing the compilation.
[0028] Type conversion annotations can also indicate the annotation lifecycle. The annotation processor processes type conversion annotations only at the source code level based on the annotation lifecycle and does not populate them into the compiled bytecode file to avoid leakage of annotation information at runtime.
[0029] The annotation processor can also cache diagnostic results in the diagnostic field of the generation task (e.g., ERROR / WARNING). Diagnostic results may include, for example, the annotation processor's syntax / semantic parsing problems of type conversion annotations and annotated element outputs, the specific location of the problems and repair suggestions, so as to process as many errors as possible from runtime to compile time.
[0030] Finally, the annotation processor outputs a task list consisting of multiple generation tasks in this step, with each generation task having a unique task identifier.
[0031] In step S02, source type descriptors and target type descriptors are constructed for the annotated element and the target type expression, respectively, in the generation task. The source type descriptor and the target type descriptor are different objects of the same data model.
[0032] For each generation task, the annotation processor constructs a source type descriptor for the annotated element and a target type descriptor for the target type expression based on the same data model. Constructing source and target type descriptors on the same data model facilitates comparison between them in subsequent steps.
[0033] The type information in the source type descriptor (srcDescriptor) comes from the compiler that performed the compilation, specifically obtained through TypeMirror. TypeMirror is an abstract base class or interface for all types in the Java language. Whether it is a primitive type, class, interface, array, type variable, or wildcard, there is a corresponding TypeMirror. Due to its numerous subclasses and complex structure, the Visitor pattern is usually used to traverse and process different types of TypeMirror and determine the specific type of the TypeMirror at runtime.
[0034] The type information obtained using the TypeMirror of the annotated element is updated to the raw type in the source type descriptor. When the annotated element contains different types (DeclaredType / ArrayType / WildcardType, etc.), it obtains type information for different values. APT then calls the API (Types / Elements) to obtain parameter information for different value types and updates the parameter descriptor (params) in the source type descriptor. For example, if the raw type (rawType) in the source type descriptor comes from DeclaredType, then erasedName is taken as the raw type (rawType), and then getTypeArguments() is recursively called to construct the subtype descriptor and update it to the parameter descriptor (params); if the raw type (rawType) in the source type descriptor comes from ArrayType, its component type is recursively processed and updated to the parameter descriptor (params); if it is WildcardType, wildcard.boundKind (extends / super) and boundType (such as Number) are recorded and wildcard is updated to the parameter descriptor (params).
[0035] When constructing the target type descriptor (dstDescriptor), the raw type (rawtype) and parameter descriptor (params) information in the target type descriptor (dstDescriptor) come from the target type expression in string form, such as "Map". <String,List <string>For the expression >", a syntax tree is first generated by a lexical / syntax parser, and then the syntax tree is mapped onto the data model (when parsing simple names, the complete qualified name is completed in conjunction with the imports / package context).
[0036] If the type conversion annotation is located in a generic class / method, the generic binding of the data model is provided by the compiler at parsing time and the type variable is replaced when needed (e.g., declaring class A as class A). <t>The T in the code is bound to the Integer used in actual operation.
[0037] In step S03, a consistency check is performed on the source type descriptor and the target type descriptor of the generated task.
[0038] In step S04, it is determined whether the consistency check of the generated task can be securely converted. If so, step S05 is executed.
[0039] Steps S03 to S04 involve polling each generation task in turn on the task list output by the previous steps, performing a static consistency check on the source type descriptor and target type descriptor in the generation task, outputting diagnostic conclusions such as ERROR or WARNING, and updating the generation tasks that can be safely converted.
[0040] Consistency checks include, but are not limited to: whether the raw types in the source and target type descriptors are compatible (using `Types.isAssignable()` or rule-based judgment); whether the lengths of the parameter groups of the raw types are consistent and each item satisfies wildcard / boundary constraints (e.g., `? extends Number` vs. `Integer`); whether the array dimensions of the raw types are compatible with `componentType`; whether generic type variables can be bound to concrete types in the current context; and whether there are elements that cannot be automatically converted (e.g., the target element is `LocalDateTime`, but there is no default converter). Safe conversion during consistency checks does not require all listed conditions to be "yes," but rather requires core compatibility (such as raw types, parameter group lengths, etc.) and guaranteed conversion safety. Furthermore, safe conversion can also be performed when degradation conditions are met. Degradation conditions, such as core compatibility and non-core defects (e.g., lack of a default converter, ambiguous generic binding), can be compensated for through annotation configuration / default rules.
[0041] The above steps can be performed iteratively. That is, if the current parser cannot obtain all the information of a generation task, the task is marked and the next generation task is processed. Subsequent annotation processors retry in multiple rounds. Only when the final round still fails to parse successfully and output the corresponding diagnostic conclusion will it be recorded as a failure.
[0042] For each generation task, after verifying the consistency of the source and target type descriptors, the source and target type descriptors are updated in the generation task. Information such as custom converters and diagnostic conclusions are also updated. The updated task list is then provided to the code generator (JavaPoet / Filer for file writing).
[0043] In step S05, type-safe converter class code is generated for the generation task. The converter class code is used to implement safe type conversion when called.
[0044] The input to this step is the task list output from step S04 (each generation task contains a source type descriptor and a target type descriptor) and the configuration information of the code generator (global generation configuration, available conversion list, whether the framework is enabled, etc.). Then, the code generator (JavaPoet / Filer writes to a file) is used to generate static, type-safe, and auditable converter class code for each generation task. The converter class code embeds security enhancement logic based on type conversion annotations (null value strategy, type assertion, exception handling, immutable collection wrapper, conversion report marking, etc.), and uses deterministic naming, layered helper methods, and re-registry adaptation to ensure performance, reusability, and compatibility with mainstream frameworks.
[0045] In some more specific embodiments, generating converter class code includes the following operations.
[0046] S1. Naming and Deduplication Preparation: Generate unique class names and directories based on task identifier, package name, and target signature. The initialization task is used to record the signatures of generated helper methods (to prevent duplication). It can also provide naming and ClassLoader boundaries: generated classes use deterministic naming and package paths.
[0047] S2. Generate Private Auxiliary Transformation Methods: Based on the TypeDescriptor model, traverse the matching nodes of the source type descriptor (srcDescriptor) and the target type descriptor (dstDescriptor) from bottom to top to determine whether the matching node needs an auxiliary transformation method, and generate a private auxiliary transformation method accordingly. During this process, placeholder implementations are generated for detected circular dependency types, and these placeholders are replaced with full implementations in subsequent processing rounds.
[0048] S3. Generate top-level public method: Generate 'public static' <t>The top-level method 'TargetType convert(SourceType src)' internally calls a private helper conversion method and adds security enhancement logic at the entry point based on type conversion annotations (e.g., nullPolicy, strict).
[0049] S4: Insert security enhancement points: Insert security enhancement logic such as null handling, type assertion, exception handling, conversion report dotting, and immutable collection wrapping into the appropriate positions of the methods in the converter class output by the code generator (including top-level public conversion methods and private / package-level helper methods generated for recursion / sub-elements) according to the annotation strategy.
[0050] S5: Custom processor and registry integration point generation: Generate multi-level lookup call logic at each location where element transformation is required.
[0051] S6: Formatted comments and metadata: Insert source annotations, generator version, generation time, task identifier, etc. into the file header and methods to facilitate review.
[0052] S7: Output file: Writes to the source file, generates unit test stubs (optional), and updates the generated product list.
[0053] Finally, this step outputs the generated source / class files, the manifest file released with the artifact (default path META-INF / safeconvert / manifest.json, containing metadata such as task identifier, generated converter class name, type key, generator version, etc.; signing is optional), test stubs, and a list of generated artifacts. The manifest can be generated during compilation or packaging and is used for runtime discovery, rollback, and (optionally) signature verification. The signature key is managed by the build / operations team and is not written to the source code. The handling behavior when signature verification fails can be determined by runtime configuration (e.g., rejection / warning / rollback). The manifest file provides the technical foundation for runtime discovery, version tracking, and security verification, and is a key support for achieving the "zero-intrusion" and manageability of this disclosure.
[0054] For example, the annotated element is a Map. <String, List <integer>The compiler obtains and constructs the source type descriptor `srcDescriptor` via `TypeMirror`, and the target type expression `target` in the annotation is `"Map"`. <String, List <string>The annotation processor parses the string into a target type descriptor (dstDescriptor). Verification revealed that Integer to String requires a converter. If no converter is provided, a `convert(Map)` function can be generated. <String,List <integer>> src), to output a Map <String, List <string>> and can provide the following diagnostic conclusions: Error: [SafeConvert] File Account.java:42 - target "Map <String,List <string>>" with field type"Map <String,List <integer>The element type does not match; Recommendation: Provide a custom converter for the element type.
[0055] When the bytecode generated by the above embodiments is executed by the virtual machine, the virtual machine attempts to read the package-private metadata within the converter class. If it is unavailable, it falls back to reading the manifest file (META-INF / safeconvert / manifest.json) and verifies the signature. If the metadata conflicts with the manifest file, the metadata within the converter class takes precedence by default, or is forced to be consistent according to the configuration. Package-private means that a class, method, or field can only be accessed by other classes within the same package; classes outside the package cannot access it.
[0056] The above converter class code can be invoked by business modules in three ways: direct static invocation, dynamic registry invocation, and framework adaptation. Direct static invocation refers to the business code directly calling the secure conversion API, which is the optimal choice. Dynamic registry invocation involves using 'TypeKey' for lookup and recording the results. Framework adaptation involves registering the generated adapter as a Spring Converter or Jackson Module so that the framework prioritizes using the generated converter during serialization / injection. When the business system uses the converter class code for type conversion, the conversion process follows restrictions such as null policy and strict mode, and sensitive data is also anonymized / sampled for reporting.
[0057] In summary, this embodiment obtains the compiler's compilation strategy for annotated elements at compile time through the annotation processor, and simultaneously obtains the type conversion intent injected by the developer by parsing type conversion annotations. Without changing the business logic, it automatically generates the converter class code that will be called at runtime. This not only achieves compatibility between the compiler's compilation strategy and the developer's type conversion intent, but also advances as much verification as possible to compile time (syntax and semantic level), so that the diagnostic conclusions can provide clear location and repair suggestions during the compilation stage.
[0058] In some embodiments, annotations are used in the form `@Retention(RetentionPolicy.SOURCE)`. However, to ensure that compile-time annotation information is used controllably and securely at runtime, the generator should write the annotation configuration as "controlled metadata" when generating the converter class code. To ensure security and project compatibility, restricted-access metadata (defaulting to package-private string constants or package-private access methods) is generated within the generated class. A short JSON constant (containing only non-sensitive fields) can also be generated to avoid writing runtime sensitive information in plaintext to public constants. By default, only non-sensitive metadata is written; sensitive fields should be written as a digest or completely excluded. Adapters that read metadata at runtime should first attempt to read the package-private metadata of the generated class; if the generated converter class is not published with the artifact, it should fall back to the META-INF / safeconvert / manifest.json generated during the build phase, which is loaded by the SPI. The generator must document this fallback mechanism in its documentation. The generator can provide an optional signature (HMAC-SHA256), and the signing key is managed by the build / operations team (not written to the source code). The runtime adapter prioritizes verifying the signing key when reading the manifest (optional configuration).
[0059] Several examples are given below at the source code level.
[0060] First example: Type conversion annotations include the following entries.
[0061] 1) Target type expression: target = "Map <String,List <string>>"; 2) Null value policy: nullPolicy = NullPolicy.DEFAULT; 3) Custom converter: converters = { "com.example.LocalDateTimeConverter"}; 4) Immutable identifier: immutable = true; 5) Strict mode: strict = true; 6) Identifier: id = "Account_amounts_v1" 7) The annotated element is a private Map <String, List <integer>> amounts.
[0062] Second example: GenerationTask.
[0063] 1) Unique identifier of the source element: sourceElementId; 2) Source file path and location information: sourceFilePath; 3) Annotation raw attribute: annotationRaw; 4) Parse context information (used to parse the simple name of the target and the generic variable binding): imports / package / enclosingTypeBindings; 5) Source type (populates srcDescriptor in the TypeDescriptor stage): srcTypeMirrorPlaceholder; 6) Target type string (dstDescriptor is populated in the TypeDescriptor stage) dstTargetString; 7) Generated class naming: suggestedClassName / suggestedPackage; 8) External converters (list their types if annotations or subsequent parsing reveal that an external converter is needed): dependencyConverters; 9) Compile-time error / warning buffer placeholder: diagnostics; 10) Whether to treat incompatibility cases as ERROR: strictFlag.
[0064] Third example: A data model used to construct source type descriptors and target type descriptors.
[0065] 1) Primitive type: rawType; / / e.g., "java.util.Map" 2) Sequential generic parameter descriptors: List <typedescriptor>params; 3) Whether it is an array type: isArray; 4) Array dimension: arrayDepth; 5) Wildcard boundary information: WildcardInfo wildcard; / / (extends / super) 6) Variable name of type variable (T): typeVariableName; / / If it is a type variable (T), record the variable name. 7) Specific binding of generic variables: Map<String, TypeDescriptor> typeVariableBindings; / / Concrete binding of generic variables (T -> java.lang.Integer) in the current context. 8) Whether it is a primitive type: isPrimitive.
[0066] Fourth example: Manifest file (META-INF / safeconvert / manifest.json) META-INF / safeconvert / manifest.json [ { "taskId": "Account_amounts_v1", / / Task identifier "generatedClass" / / Name of the generated converter class "com.example.safeconvert.generated.SafeConvert_Account_amounts_v1_Impl", "typeKeys": ["java.util.Map| <java.lang.String,java.util.List|<java.lang.Integer> >"], / / Type key information "metaSummary": / / Version information, {"nullPolicy":"DEFAULT","strict":true,"specVersion":"1.0"}, "signature": "HMAC-SHA256(base64(metadataJson), base64(hmacKeyId))" / / Version signature } ] Accordingly, the compile-time type conversion generation method for zero intrusion provided in the above embodiments can be formed into a computer program consisting of executable computer instructions and stored in a computer-readable storage medium. Figure 2 The workflow for compiling and executing computer programs based on the embodiments described above is given.
[0067] As shown in the figure, compiler 120 can be implemented on one or more computing devices and can receive source code 110 for computer programs. In various embodiments, source code 110 can be based on a variety of high-level and / or platform-independent, object-oriented programming languages. For example, in embodiments using Java™, the source code can be provided as a set of .java files. In some embodiments, source code 110 can be specified using a combination of languages that may include one or more low-level and / or intermediate languages (e.g., assembly). In some embodiments, at least some of the source code may initially be written in a dynamically typed high-level language such as Python or Ruby.
[0068] Compiler 120 can analyze source code 110 to produce an executable version of the program or bytecode file 130, for example, in the case of JavaTM, file 130 is a .class file or a .jar file. Different types of executable code formats can be used in various embodiments; for example, binary machine language can be used instead of bytecode. In some scenarios, parts of executable code 130 may be bytecode, while other parts are native binary machine language.
[0069] The compiler 120 can also perform a series of analysis operations and generate various intermediate codes before generating the executable or bytecode file 130. For example, as described in the above embodiments, safe type conversion can be achieved using type conversion annotations set at program elements. The compiler creates type-safe converter class code 140 based on the type conversion annotations, and the converter class code 140 can be compiled by the compiler 120 along with the source code 110 to generate the executable or bytecode file 130, thereby achieving safe type conversion during the compilation stage. The compiler can also output error messages for unsafe type conversions based on the type conversion annotations, thereby detecting and handling unsafe type conversions during the compilation stage. In some embodiments, the compiler can also apply type erasure operations to generics to create an annotated class file 130, where the annotations can indicate which type variables have been erased and which types are metadata of the erased type variables.
[0070] In some embodiments, compiler 120 may retain only the type conversion annotations and the non-sensitive portions of the converter class code 140 generated therefrom. For example, in one embodiment, compiler 120 may retain only the information used as part of the erasure process.
[0071] like Figure 2 As shown, the executable or bytecode file 130 can be passed to an execution environment that executes code on the execution platform 200, such as the runtime environment of a virtual machine 220 located in the operating system 210, thereby creating various output data and / or behaviors. According to various embodiments, the runtime environment of the virtual machine 220 may further include multiple different components, such as a memory manager, a class loader, a bytecode verifier (e.g., to check the validity of the executable code), and / or an interpreter and / or a just-in-time (JIT) compiler. In some embodiments, the JIT compiler may be responsible for translating some or all of the bytecode (e.g., frequently used portions of the bytecode) into platform-specific machine code to improve program execution performance. In some embodiments, the runtime environment of the virtual machine 220 may also include code implementing multiple application programming interface (API) libraries.
[0072] The embodiments of this disclosure are as described above. These embodiments do not exhaustively describe all details, nor do they limit the invention to the specific embodiments described. Obviously, many modifications and variations can be made based on the above description. This specification selects and specifically describes these embodiments to better explain the principles and practical applications of the embodiments of this disclosure, thereby enabling those skilled in the art to make good use of the embodiments of this disclosure and modifications based on them. The embodiments of this disclosure are limited only by the claims and their full scope and equivalents.< / typedescriptor> < / integer> < / string> < / integer> < / string> < / string> < / integer> < / string> < / integer> < / t> < / t> < / string>
Claims
1. A zero-invasive compile-time type conversion generation method, characterized in that, include: Scan and parse type conversion annotations in the source code, and build generation tasks for the type conversion annotations, the generation tasks indicating the annotated element information and the target type expression; For each generation task, a source type descriptor is constructed for the annotated element, and a target type descriptor is constructed for the target type expression, wherein the source type descriptor and the target type descriptor are based on the same data model; Perform a consistency check on the source type descriptor and the target type descriptor in each generation task; A generation task for secure type conversion is performed on consistency checks, generating type-safe converter class code. This converter class code embeds security enhancement logic based on type conversion annotations, and implements secure type conversion when called. The generation of type-safe converter class code includes: A bottom-up traversal is performed on the matching nodes of the target type descriptor and the source type descriptor to determine whether a matching node requires an auxiliary conversion method, and a private auxiliary conversion method is generated accordingly; and Generate a top-level public conversion method, which internally calls the private auxiliary conversion method and integrates security enhancement logic based on the type conversion annotation.
2. The method of claim 1, wherein, Constructing a source type descriptor for an annotated element includes: The compiler-provided type information is used to obtain the primitive type and parameter information of the annotated element as specified by the compiler, and then the primitive type and parameter group in the source type descriptor are updated accordingly. Constructing a target type descriptor for the target type expression includes: Perform lexical or syntactic analysis on the target type expression and generate a syntax tree; and The syntax tree is mapped to the target type descriptor based on the parsing context, and the values of the primitive type and parameter group in the target type descriptor are derived from the target type expression.
3. The compile-time type conversion generation method of claim 2, wherein, The consistency check includes checking whether the original types in the source type descriptor and the target type descriptor are compatible and whether the lengths of the parameter groups are consistent.
4. The method of claim 1, wherein, When generating the private auxiliary conversion method, a placeholder implementation is generated for the detected circular dependency type, and then replaced with the full implementation in subsequent processing rounds.
5. The compile-time type conversion generation method according to claim 1, characterized in that, The security enhancement logic includes one or more of the following: null value handling, type assertion, exception handling, immutable collection wrapping, and conversion report marking.
6. The compile-time type conversion generation method according to claim 1, characterized in that, The method further includes: A manifest file is generated during compilation. The manifest file includes a task identifier, the name of the generated converter class, a type key, version information, and a signature.
7. The compile-time type conversion generation method according to claim 1, characterized in that, Also includes: The converter class code can be invoked in one of the following ways: The business logic code directly calls the generated converter class statically; The converter is dynamically searched and invoked based on the type key in the runtime registry; The generated converter is registered to the application framework's conversion service via the framework adapter.
8. A computing device comprising a memory and a processor, wherein the memory stores a computer program, characterized in that, When the processor executes the computer program, it implements the steps of the compile-time type conversion generation method as described in any one of claims 1 to 7.
9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the compile-time type conversion generation method as described in any one of claims 1 to 7.
Citation Information
Patent Citations
Code conversion method and device based on domain-specific language and medium
CN120610708A