Note processing method and device, electronic equipment and storage medium

By automatically overriding the toString() method using class-level and field-level annotations in Java code, the lack of intuitiveness and practicality of the toString() method is resolved, improving code development efficiency and maintainability.

CN121900809APending Publication Date: 2026-04-21AVATR CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
AVATR CO LTD
Filing Date
2025-12-03
Publication Date
2026-04-21

AI Technical Summary

Technical Problem

In Java programming, the default output of a class's toString() method lacks intuitiveness and practicality, forcing developers to manually rewrite it, which increases code redundancy and the risk of errors.

Method used

By adding class-level and field-level annotations to the source code, the toString() method is automatically overridden to generate a string representation with a uniform format and high readability, reducing manual intervention and ensuring source code consistency and maintainability.

Benefits of technology

It significantly reduces the risk of coding errors, improves code development efficiency and maintainability, ensures the flexibility and consistency of annotation configuration, and shortens the bytecode file build time.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121900809A_ABST
    Figure CN121900809A_ABST
Patent Text Reader

Abstract

The invention relates to the technical field of computers, and discloses an annotation processing method and device, electronic equipment and a storage medium, the annotation processing method comprises the following steps: obtaining a class-level annotation added for a target class by a user in a source code, the class-level annotation being used for defining and configuring class attributes of the target class; when a source code compiling instruction is received, the source code of the target class is rewritten based on the class-level annotation, and the first byte code file corresponding to the class-level annotation is compiled and generated, errors caused by coding negligence can be greatly reduced, meanwhile, repeated logic in the source code is eliminated, and the overall development efficiency and maintainability of codes are remarkably improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer technology, and more specifically to annotation processing methods, apparatus, electronic devices, and storage media. Background Technology

[0002] In Java programming, all classes inherit from the Object class, whose toString() method is used to provide a string representation of an object. However, in practice, the default toString() output often lacks intuitiveness or practicality, so developers often need to manually override this method, which not only easily leads to errors but also increases code redundancy. Summary of the Invention

[0003] This invention provides an annotation processing method, apparatus, electronic device, and storage medium to address the problem that the default toString() output in related technologies often lacks intuitiveness or practicality, thus requiring developers to manually rewrite the method, which not only easily leads to errors but also increases code redundancy.

[0004] In a first aspect, the present invention provides an annotation processing method, comprising: obtaining class-level annotations added by the user for a target class in the source code, wherein the class-level annotations are used to define and configure class attributes of the target class; and when a source code compilation instruction is received, rewriting the source code of the target class based on the class-level annotations, and compiling to generate a first bytecode file corresponding to the class-level annotations.

[0005] The annotation processing method provided by this invention parses class-level annotations and generates the toString() method of the target class during the compilation phase. It then concatenates field information according to the attributes defined in the annotation to generate a string representation with a uniform format and high readability, without requiring manual intervention from the developer. This significantly reduces errors caused by coding negligence, eliminates repetitive logic in the source code, and significantly improves the overall development efficiency and maintainability of the code.

[0006] In one optional implementation, adding class-level annotations to the target class includes: responding to a user's request for class annotations for the target class; obtaining the output format type and field inclusion rules of the target class's source code based on the class annotation request; defining and configuring the class attributes of the target class based on the output format type and field inclusion rules to obtain class annotation configuration parameters; and generating and inserting class-level annotations into the source code according to the class annotation configuration parameters.

[0007] The annotation processing method provided by this invention can quickly define the output format type and field inclusion rules based on the user-initiated class annotation request, without having to manually write or modify the underlying code logic. This not only further reduces the risk of coding errors and improves the consistency and flexibility of class attribute configuration, but also reduces development time and enhances the readability and maintainability of the source code.

[0008] In one optional implementation, when a source code compilation instruction is received, the source code of the target class is rewritten based on class-level annotations, and compiled to generate a first bytecode file corresponding to the class-level annotations, including: when a source code compilation instruction is received, the source code of the target class is rewritten based on class-level annotations to obtain a first source code string; the first source code string is compiled to generate a first bytecode file corresponding to the class-level annotations.

[0009] The annotation processing method provided by this invention reduces the need for manual intervention by developers during the compilation stage by automatically rewriting the source code of the target class and generating the first bytecode file, thereby reducing the risk of syntax errors or logical inconsistencies caused by human negligence. At the same time, class-level annotations not only ensure the consistency between the source code string and the bytecode file, but also improve the compilation efficiency of the source code and shorten the bytecode file construction time.

[0010] In an optional implementation, the method further includes: obtaining field-level annotations added by the user to the fields of the target class in the source code, wherein the field-level annotations are used to define and configure the field attributes of the target class; when a source code compilation instruction is received, rewriting the source code of the target class based on the field-level annotations, and compiling to generate a second bytecode file corresponding to the field-level annotations.

[0011] The annotation processing method provided by this invention defines and configures field attributes based on field-level annotations, eliminating the need for developers to manually write or modify the underlying code. This further reduces the risk of field attribute errors or inconsistencies caused by human intervention. Simultaneously, by rewriting the source code based on field-level annotations and generating a second bytecode file, it not only ensures real-time synchronization and high consistency of field attribute configurations but also significantly improves code maintainability and flexibility, drastically shortens the construction time of field-related bytecode files, thereby improving the overall efficiency of software development and enhancing the readability of the source code.

[0012] In one optional implementation, adding field-level annotations to the target class includes: responding to a user's request for field annotations of the target class; obtaining the field aliases and field output formats of the target class based on the field annotation request; defining and configuring the field attributes of the target class based on the field aliases and field output formats to obtain field annotation configuration parameters; and generating and inserting field-level annotations into the source code according to the field annotation configuration parameters.

[0013] The annotation processing method provided by this invention greatly simplifies the process of adding field-level annotations by responding to annotation requests and extracting configuration parameters such as field aliases and output formats; by dynamically generating annotation configuration parameters based on user-defined field aliases and output formats, it can ensure the flexibility and accuracy of field attribute configuration; by directly inserting standardized field-level annotations into the source code, it can effectively avoid manual coding errors, improve the standardization level of field attribute definitions, and at the same time improve code maintainability and development efficiency.

[0014] In one optional implementation, when a source code compilation instruction is received, the source code of the target class is rewritten based on field-level annotations, and a second bytecode file corresponding to the field-level annotations is generated. This includes: when a source code compilation instruction is received, the source code of the target class is rewritten based on class-level annotations and field-level annotations to obtain a second source code string; the second source code string is compiled to generate a second bytecode file corresponding to the class-level annotations.

[0015] The annotation processing method provided by this invention significantly reduces the risk of errors that may be introduced by manually modifying the source code by rewriting the source code based on class-level annotations and field-level annotations; by directly compiling the annotation information into the bytecode file, it effectively ensures the consistency between the runtime annotation configuration and the source code definition; and by generating a second source code string, it further improves the reliability and development efficiency of the source code compilation process.

[0016] In an optional implementation, the method further includes: when the source code is run directly without being compiled, intercepting the class-level annotations and field-level annotations when the source code runs to the class-level annotations or field-level annotations of the target class; rewriting the source code of the target class based on the intercepted class-level annotations and field-level annotations, and generating the corresponding third-bytecode file.

[0017] The annotation processing method provided by this invention significantly reduces the risk of errors caused by manual intervention by dynamically intercepting and processing class-level and field-level annotations when the source code is run directly without compilation. By rewriting the source code in real time and generating a third-party bytecode file, it effectively ensures the consistency between runtime annotation configuration and source code definition, avoiding configuration deviations caused by direct execution. At the same time, this implementation method further enhances the flexibility of the development and testing phases, facilitating rapid iterative verification by developers without additional compilation steps, thereby greatly improving development efficiency and overall system reliability.

[0018] Secondly, the present invention provides an annotation processing apparatus, comprising: an annotation acquisition module, configured to acquire class-level annotations added by a user to a target class in the source code, wherein the class-level annotations are used to define and configure class attributes of the target class; and an annotation processing module, configured to rewrite the source code of the target class based on the class-level annotations when a source code compilation instruction is received, and compile to generate a first bytecode file corresponding to the class-level annotations.

[0019] Thirdly, the present invention provides an electronic device, comprising: a memory and a processor, wherein the memory and the processor are communicatively connected to each other, the memory stores computer instructions, and the processor executes the computer instructions to perform the annotation processing method of the first aspect or any corresponding embodiment described above.

[0020] Fourthly, the present invention provides a computer-readable storage medium storing computer instructions for causing a computer to perform the annotation processing method of the first aspect or any corresponding embodiment described above.

[0021] Fifthly, the present invention provides a computer program product, including computer instructions for causing a computer to execute the annotation processing method of the first aspect or any corresponding embodiment described above. Attached Figure Description

[0022] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.

[0023] Figure 1 This is a schematic flowchart of the first type of annotation processing method according to an embodiment of the present invention; Figure 2 This is a schematic diagram of a second type of annotation processing method according to an embodiment of the present invention; Figure 3 This is a schematic diagram of the third process of the annotation processing method according to an embodiment of the present invention; Figure 4 This is a structural block diagram of an annotation processing apparatus according to an embodiment of the present invention; Figure 5 This is a schematic diagram of the hardware structure of an electronic device according to an embodiment of the present invention. Detailed Implementation

[0024] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0025] It is understood that before using the technical solutions disclosed in the various embodiments of the present invention, users should be informed of the types, scope of use, and usage scenarios of the personal information involved in the present invention and their authorization should be obtained in accordance with relevant laws and regulations through appropriate means.

[0026] The terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature. In the description of this invention, "a plurality of" means two or more, unless otherwise explicitly specified.

[0027] According to an embodiment of the present invention, an annotation processing method embodiment is provided. It should be noted that the steps shown in the flowchart in the accompanying drawings can be executed in a computer system such as a set of computer-executable instructions. Furthermore, although a logical order is shown in the flowchart, in some cases, the steps shown or described may be executed in a different order than that shown here.

[0028] This embodiment provides an annotation processing method. Figure 1 This is a flowchart of an annotation processing method according to an embodiment of the present invention, such as... Figure 1 As shown, the process includes the following steps: Step S101: Obtain the class-level annotations added by the user for the target class in the source code.

[0029] Among them, class-level annotations are used to define and configure the class attributes of the target class.

[0030] Specifically, the class-level annotation @ToString is used to configure the overall format of the class's toString() method, and includes the following attributes: format(): Specifies the output format type (enumeration values: SIMPLE, JSON, XML, CUSTOM), default is SIMPLE; includeAllFields(): Whether to include all fields; the default is true. excludeFields(): An array of field names to exclude; the default is empty.

[0031] In some optional implementations, when adding class-level annotations to a target class, the system can respond to user requests for class annotations for the target class; based on the class annotation requests, obtain the output format type and field inclusion rules of the target class's source code; based on the output format type and field inclusion rules, define and configure the class attributes of the target class to obtain class annotation configuration parameters; and generate and insert class-level annotations into the source code according to the class annotation configuration parameters.

[0032] Specifically, users can initiate class annotation requests through integrated development tools (such as IDE plugins) or API interfaces. Upon receiving the request, the system parses the source code structure of the target class, identifies its output format type (e.g., JSON, XML, SIMPLE, CUSTOM, custom format SpEL (Spring Expression Language), or similar syntax placeholders to reference fields), and generates class attribute configuration parameters based on preset field inclusion rules (e.g., including only public fields, ignoring private fields, or including all inherited fields). Subsequently, these class attribute configuration parameters are mapped to specific class-level annotation syntax (e.g., using Java's @ToString format) and inserted into the class definition location in the source code, ensuring seamless integration of annotations and code logic. Users can also verify the configuration effect using the real-time preview function.

[0033] As an example, suppose the target class is User, whose source code contains public fields `name` (string type) and `age` (integer type), and a private field `password`. When a user requests a class annotation through an IDE plugin or API, specifying the output format as JSON and setting the field inclusion rule to include only public fields, the source code structure of the User class is parsed, the public fields `name` and `age` are identified, and the private field `password` is ignored. Based on the user configuration, class annotation configuration parameters are generated, such as `@ToString(format = Format.JSON, includeAllFields = false)`, and this annotation is inserted into the class definition of the User class. After insertion, the user can verify the effect through the real-time preview function. For example, when calling the `toString` method, the output result will only contain JSON format data of the public fields, such as `{"name":"John","age":30}`. If the user modifies the configuration, such as changing the output format to SIMPLE or including all fields, the annotation parameters will be updated to ensure seamless integration with the code logic. In addition, during the annotation insertion process, field validity needs to be checked to avoid referencing non-existent fields, and corresponding compilation prompts are generated to assist users in adjusting the configuration.

[0034] As another example, suppose the target class is Order, whose source code contains public fields orderId (string type), items (list type), and total (floating-point type), as well as a private field customerInfo. When a user initiates a class annotation request through the API interface, specifies the output format type as CUSTOM, uses a custom format SpEL expression such as "#{item.name}:#{item.quantity}" as a placeholder, and sets the field inclusion rule to include only public fields, the source code structure of the Order class is parsed to identify the public fields orderId, items, and total. Based on the user configuration, class annotation configuration parameters are generated, such as @ToString(format =Format.CUSTOM,expression= "#{item.name}:#{item.quantity}", includeAllFields = false), and this annotation is inserted into the class definition of the Order class. After insertion, the user can verify the effect through the real-time preview function. For example, when calling the toString method, the output result will be formatted according to the custom expression for the public field data, such as "Laptop:2,Monitor:1". If the user adjusts the configuration, such as changing the field inclusion rule to include all fields or modifying the expression syntax, the annotation parameters will be dynamically updated to ensure seamless integration with the code logic. At the same time, the validity of the expression will be checked to avoid compilation errors, and prompts will be generated to help the user optimize the settings.

[0035] As shown above, output format types and field inclusion rules can be quickly defined based on user-initiated class annotation requests, without the need to manually write or modify the underlying code logic. This not only further reduces the risk of coding errors and improves the consistency and flexibility of class attribute configuration, but also reduces development time and enhances the readability and maintainability of the source code.

[0036] Step S102: When the source code compilation instruction is received, the source code of the target class is rewritten based on the class-level annotations, and the first bytecode file corresponding to the class-level annotations is generated.

[0037] The source code compilation instruction can be triggered by the user through the build menu of the integrated development environment (IDE), or automatically issued by the build tool (such as Maven or Gradle) in the project build process. The source code compilation instruction carries the target class identifier and compilation parameters, which are used to instruct the compiler to perform source code rewriting operations after parsing class-level annotations, ensuring that the generated bytecode file strictly follows the serialization rules defined by the annotation.

[0038] In some optional implementations, if a source code compilation instruction is received, and the source code of the target class is rewritten based on the class-level annotations and compiled to generate the first bytecode file corresponding to the class-level annotations, the source code of the target class can be rewritten based on the class-level annotations to obtain the first source code string when the source code compilation instruction is received; the first source code string is then compiled to generate the first bytecode file corresponding to the class-level annotations.

[0039] Specifically, the rewriting process includes parsing the serialization rules in class-level annotations, such as field types, format constraints, and inclusion logic, and generating a new source code string that conforms to the rules; the compilation process can use a Java compiler or equivalent tools to perform syntax checks and bytecode conversion on the first source code string according to the compilation parameters to ensure that the generated bytecode file fully complies with the annotation definition.

[0040] As an example, suppose a target class is defined as `@Serializable(format = "JSON", includeFields = {"id", "name"}, excludeFields = {"password"})`. Upon receiving the source code compilation instructions, the parser parses the serialization rules in this annotation, identifying that the `id` and `name` fields must be included, while excluding the `password` field. During the rewrite process, the newly generated source code string introduces a `serializeToJson()` method, which automatically constructs a string output conforming to JSON format, ensuring that field types (e.g., `id` is an integer, `name` is a string) and format constraints (e.g., field name case conversion) are strictly applied. Subsequently, the compiler uses the Java Compiler API to perform syntax validation and bytecode conversion on the modified source code string. The generated first bytecode file contains optimized serialization logic, enabling efficient handling of object serialization tasks at runtime.

[0041] As another example, for a User class annotated with `@ToString`, when the annotation specifies the serialization format as JSON and includes specific fields (such as "username" and "email"), the rewrite process parses these rules, removes the code logic related to the unannotated fields in the original class, and generates a new source code string containing only the serialization logic for the username and email fields. Subsequently, the Java compiler performs syntax validation and bytecode conversion on this string based on compilation parameters (such as `-target 1.8`), ensuring that the final generated first bytecode file strictly adheres to the annotation constraints, avoiding runtime serialization errors, and improving code execution efficiency.

[0042] As shown above, by automatically rewriting the source code of the target class and generating the first bytecode file, the need for manual intervention by developers during the compilation phase is reduced, and the risk of syntax errors or logical inconsistencies caused by human negligence is lowered. At the same time, class-level annotations not only ensure the consistency between the source code string and the bytecode file, but also improve the compilation efficiency of the source code and shorten the bytecode file build time.

[0043] The annotation processing method provided in this embodiment parses class-level annotations and generates the toString() method of the target class during the compilation phase. It then concatenates field information according to the attributes defined in the annotation to generate a string representation with a uniform format and high readability, without requiring manual intervention from the developer. This significantly reduces errors caused by coding negligence, eliminates repetitive logic in the source code, and significantly improves the overall development efficiency and maintainability of the code.

[0044] This embodiment provides an annotation processing method. Figure 2 This is a flowchart of an annotation processing method according to an embodiment of the present invention, such as... Figure 2 As shown, the process includes the following steps: Step S201: Obtain the field-level annotations added by the user to the fields of the target class in the source code.

[0045] Field-level annotations are used to define and configure field attributes of the target class.

[0046] Specifically, the field-level annotation @ToStringField is used to configure the output rules for a single field and includes the following attributes: include(): Whether to include the field, defaults to true (can override the includeAllFields annotation of the class); alias(): An alias for a field (e.g., the field userName is displayed as "username"); formatter(): The formatter for the field value (e.g., specifying "yyyy-MM-dd" for a date field).

[0047] In some optional implementations, when adding field-level annotations to a target class, the system can respond to user requests for field annotations of the target class; based on the field annotation requests, obtain the field aliases and field output formats of the target class; based on the field aliases and field output formats, define and configure the field attributes of the target class to obtain field annotation configuration parameters; and generate and insert field-level annotations into the source code according to the field annotation configuration parameters.

[0048] Specifically, in the user interface, users select a specific field of the target class (such as `birthDate`) using a visual tool, input a custom alias (such as "birthday") and formatting rules (such as "yyyy-MM-dd"), parse the input parameters, and generate the corresponding field-level annotation `@ToStringField`. Subsequently, this annotation is inserted in real-time into the source code editor, ensuring that the alias and formatting rules are automatically applied when the field is output, improving code readability and flexibility. Furthermore, multiple field annotation requests can be processed in batches, dynamically loading field attributes through configuration files or API interfaces, reducing manual coding workload while maintaining seamless integration with class-level annotations (such as `@ToString`).

[0049] As an example, when a user processes a Customer class, selects the emailAddress field, enters the alias "email address" with the format rule "convert to lowercase and hide some characters (e.g., user@***.com)", and after parsing this parameter, the corresponding @ToStringField(name="email address", mask="***") annotation is generated and inserted into the source code in real time. When the object's toString() method is called, the emailAddress field will output "email address: user@***.com", effectively protecting user privacy. Simultaneously, developers can predefine attributes for multiple fields through configuration files (such as YAML files), for example, setting the alias for the Address field as "address" and the format "province-city-district", batch loading and applying annotations, ensuring rapid integration of class-level annotations @ToString in large projects, avoiding manual coding errors, and improving development efficiency.

[0050] As shown above, by responding to annotation requests and extracting configuration parameters such as field aliases and output formats, the process of adding field-level annotations is greatly simplified; by dynamically generating annotation configuration parameters based on user-defined field aliases and output formats, the flexibility and accuracy of field attribute configuration can be guaranteed; by directly inserting standardized field-level annotations into the source code, manual coding errors can be effectively avoided, the standardization level of field attribute definitions can be improved, and the maintainability and development efficiency of the code can be enhanced.

[0051] Step S202: When the source code compilation instruction is received, the source code of the target class is rewritten based on the field-level annotations, and the second bytecode file corresponding to the field-level annotations is generated.

[0052] The bytecode file includes the class definition after applying annotations.

[0053] In some optional implementations, when a source code compilation instruction is received, the source code of the target class is rewritten based on field-level annotations and compiled to generate a second bytecode file corresponding to the field-level annotations. Alternatively, when a source code compilation instruction is received, the source code of the target class is rewritten based on class-level annotations and field-level annotations to obtain a second source code string; the second source code string is then compiled to generate a second bytecode file corresponding to the class-level annotations.

[0054] Specifically, the process of rewriting the source code of a target class based on class-level and field-level annotations includes the following steps: First, an annotation processor (such as AbstractProcessor) identifies the class-level annotation `@ToString` declared in the target class and extracts its predefined configuration parameters, such as field aliases and output formats. Second, iterates through all fields of the target class and, combined with the configuration attributes of the field-level annotation `@ToStringField`, dynamically generates source code fragments containing standardized formats. Then, these source code fragments are merged into the original source code, replacing or enhancing the original field definitions to form a second source code string. For example, when a class-level annotation specifies a unified output format (such as "province-city-district"), the annotation processor injects corresponding formatting logic into each relevant field to ensure that the generated second source code string conforms to the predefined standard. Finally, the second source code string is compiled using a Java compiler (such as `javac`), and then a second bytecode file is generated using tools such as JavaPoet. This file not only contains the application effects of field-level annotations but also fully implements the global configuration of class-level annotations, while improving the efficiency of formatted output during the runtime of the target class's source code.

[0055] As an example, define a target class Address that contains address information. A class-level annotation @ToString(format = "Province-City-District") is added to the class declaration, and field-level annotations @ToStringField are added to its three fields: province, city, and district. After the annotation processor recognizes @ToString, it obtains the specified unified format string "Province-City-District". Subsequently, when traversing the fields, corresponding formatted code snippets are dynamically generated for these three fields. For example, for the province field, code like String formattedProvince = formatField(this.province, "Province") is generated (where formatField is a processing method generated according to the annotation logic). These snippets are combined, and finally the toString() method of this class is rewritten (or newly created) to return a string concatenated in the "Province-City-District" format. When the second bytecode file generated after compilation is executed, its toString() method will directly output the formatted address information without performing additional string parsing operations at runtime, thus improving the efficiency of object serialization or log output.

[0056] As described above, by rewriting the source code based on class-level and field-level annotations, the risk of errors introduced by manual modification of the source code is significantly reduced; by directly compiling the annotation information into the bytecode file, the consistency between the runtime annotation configuration and the source code definition is effectively ensured; by generating the second source code string, the reliability and development efficiency of the source code compilation process are further improved.

[0057] In some optional embodiments, when receiving a source code compilation instruction, based on field-level annotations to rewrite the source code of the target class and compile and generate a second bytecode file corresponding to the field-level annotations, potential conflicts in field annotations can be detected and repaired during the compilation process. For example, when multiple annotations act on the same field, the user-defined priority rules are preferentially adopted to ensure the consistency of the output format; in addition, a detailed operation report can be generated when rewriting the source code, including the field alias mapping status and format conversion results, which is convenient for users to monitor and debug in real time, thereby enhancing the traceability and robustness of the system while improving the compilation efficiency.

[0058] Specifically, when detecting potential conflicts, all field-level annotations can be scanned first to identify whether multiple annotations are applied to the same field simultaneously. If a conflict is detected, the effective annotation is automatically selected based on user-defined priority rules (such as setting the execution order or weight value of annotations through configuration files) to avoid output format confusion. For example, in the user definition, annotation A has a higher priority than annotation B. When both are applied to the same field, annotation B will be ignored, and only the rules of annotation A will be applied, thus avoiding format conflicts. At the same time, the conflict resolution process is recorded in the operation report, including the identifier of the ignored annotation and the details of the applied rules, making it convenient for users to trace back and verify the compilation results through logs.

[0059] The annotation processing method provided by this invention defines and configures field attributes based on field-level annotations, eliminating the need for developers to manually write or modify the underlying code. This further reduces the risk of field attribute errors or inconsistencies caused by human intervention. Simultaneously, by rewriting the source code based on field-level annotations and generating a second bytecode file, it not only ensures real-time synchronization and high consistency of field attribute configurations but also significantly improves code maintainability and flexibility, drastically shortens the construction time of field-related bytecode files, thereby improving the overall efficiency of software development and enhancing the readability of the source code.

[0060] As one or more specific application embodiments of this invention, the parsing timing of class-level annotations and field-level annotations can be defined using `@String(model=Model.compile)`. Here, `Model.compile` is parsed at compile time. If a user adds a class-level annotation to the target class and field-level annotations to the fields of the target class, during the compilation phase, `AbstractProcessor` can scan classes annotated with `@ToString`, parse the annotation attributes and field information, generate the source code string of the `toString()` method, and then use tools such as JavaPoet to generate bytecode, resulting in a second bytecode file.

[0061] Here is an example of an implementation that overrides the ToString method: / / Output format.

[0062] public enum Format { SIMPLE, JSON, XML, CUSTOM ; } public @interface ToString { / / Output format.

[0063] Format format() default Format.SIMPLE; / / Output the renamed fields.

[0064] String alias() default""; / / Output only the specified fields.

[0065] String[] includeFields() default {}; / / Exclude specified fields.

[0066] String[] excludeFields() default {}; / / Custom template.

[0067] String template() default ""; } @AutoService(Processor.class) @SupportedAnnotationTypes("com.example.ToString") / / Annotations to be processed.

[0068] @SupportedSourceVersion(SourceVersion.RELEASE_7) / / Supported Java versions.

[0069] public class ToStringProcessor extends AbstractProcessor { @Override public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv) { final Context context = ((JavacProcessingEnvironment) processingEnv).getContext(); final JavacElements elementUtils = (JavacElements)processingEnv.getElementUtils(); final TreeMaker treeMaker = TreeMaker.instance(context); Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(ToString.class); for (Element element : annotatedElements) { / / Rewrite the logic of the toString method based on the ToString annotation configuration.

[0070] } } Furthermore, when generating bytecode using tools such as JavaPoet, you can first define an interface Formatter, which includes the method String format(class...<?> clazz,List <fieldinfo>fields, ToString annotation), where FieldInfo encapsulates information such as field names, values, aliases, formatters, etc. During compilation, according to the ToString annotation configuration output type, the corresponding formatter class is called through the strategy pattern. The implementation classes include: SimpleFormatter: A simple format processor that generates a format like "class name{field1 = value1, field2 = value2}"; JsonFormatter: A JSON format processor that generates a JSON format string (e.g., {"field1":"value1", "field2":"value2"}); XmlFormatter: An XML format processor that generates an XML format (e.g., <class name><field1>value1< / field1>< / class name>); CustomFormatter: A custom format processor that generates a formatted output according to a custom template.

[0071] / / Example of the target class.

[0072] @ToString(format = Format.JSON, excludeFields = {"password"}) public class User { private String name; @ToStringField(alias = "Password", include = false) / / Override the class annotation to force exclusion.

[0073] private String password; private int age; @ToStringField(alias = "Registration Time", formatter = "yyyy - MM - dd") private Date registerTime; / / Omit getters / setters.

[0074] } / / Usage in program coding.

[0075] User user = new User("admin", 25, new Date()); / / Format without using annotations System.out.println(user); / / Output: User @96532d6.

[0076] / / Use the default annotation format @ToString(format=Format.SIMPLE).

[0077] System.out.println(user); / / Output: User {name='admin', age=25,registerTime=Tue Nov 04 16:11:23 CST 2025}.

[0078] / / Use the JSOM annotation to format @ToString(format=Format.JSON).

[0079] System.out.println(user); / / Output: {"name":"admin","age":25,"registerTime":"Tue Nov 04 16:11:23 CST 2025"}.

[0080] ... This embodiment provides an annotation processing method. Figure 3 This is a flowchart of an annotation processing method according to an embodiment of the present invention, such as... Figure 3 As shown, the process includes the following steps: Step S301: When the source code is run directly without being compiled, intercept the class-level annotations and field-level annotations when the source code runs to the class-level annotations or field-level annotations of the target class.

[0081] Running source code directly without compilation refers to the process where source code is dynamically interpreted and executed in the runtime environment without needing to be converted into bytecode or machine code by a compiler beforehand.

[0082] Step S302: Rewrite the source code of the target class based on the intercepted class-level annotations and field-level annotations, and generate the corresponding third bytecode file.

[0083] Specifically, the `@String(model=Model.running)` method defines when class-level and field-level annotations are parsed. `Model.running` specifies runtime parsing. If a user adds a class-level annotation to the target class and a field-level annotation to a field of the target class, during runtime, when the program reaches the `toString()` annotation of the target class or the `@ToStringField` annotation of a field of the target class, an interceptor is triggered. The interceptor parses the attribute parameters defined in the annotations, such as the field's display name, formatting rules, or ignore conditions, based on the configuration of the `@ToString` and `@ToStringField` annotations, thereby dynamically constructing a string representation of the target class. For example, when the `@ToString` annotation specifies `includeFieldNames=true`, the interceptor will include the field name in the output; while the `@ToStringField` annotation can set a custom format for a single field (such as "yyyy-MM-dd" for a date field), ensuring that accurate and customizable `toString()` output is generated at runtime without recompiling the source code. Simultaneously, a corresponding third-party bytecode file is generated to persist the modified class behavior, ensuring consistency in subsequent calls.

[0084] As an example, a user defines an `Employee` class and adds the `@ToString(includeFieldNames = true)` annotation to the class and the `@ToStringField(format ="yyyy-MM-dd")` annotation to the `birthDate` field. When the program instantiates an `Employee` object at runtime and calls its `toString()` method, an interceptor is triggered. Recognizing that the class-level `@ToString` annotation requires field names and that the `birthDate` field has specific date format requirements, the interceptor dynamically generates a string output similar to `Employee(name=John Doe, id=123, birthDate=2023-10-27)`, precisely applying the rules defined in the annotation. This process is completed at runtime without modifying the `Employee` class's source code or recompiling. The generated bytecode file containing this dynamic `toString()` logic is saved to ensure consistent `toString()` behavior in subsequent calls to this instance.

[0085] As another example, a user defines a `Product` class and adds the `@ToString(includeFieldNames=false)` annotation to the class and the `@ToStringField(format = "currency")` annotation to the `price` field. When the program instantiates a `Product` object at runtime and calls its `toString()` method, the interceptor is triggered. It recognizes that the class-level annotation `@ToString` requires the exclusion of field names and discovers that the `price` field has specific currency format requirements. Based on this, the interceptor dynamically generates a string output similar to `Product(Widget, $19.99)` to accurately adapt to the rules defined in the annotation. This is done at runtime without modifying the source code of the `Product` class or recompiling. The generated bytecode file containing this dynamic `toString()` logic is saved to ensure consistent `toString()` behavior in subsequent calls to this instance.

[0086] As another example, a user defines an `Order` class and adds the `@ToString(includeFieldNames=true)` annotation to the class and the `@ToStringField(format = "yyyy-MM-dd HH:mm")` annotation to the `orderDate` field. When the program instantiates an `Order` object and calls the `toString()` method at runtime, the interceptor is triggered. It recognizes that the class-level annotation `@ToString` requires field names and that the `orderDate` field has date and time format requirements. Based on this, the interceptor dynamically generates a string output similar to `Order(orderId=1001, customer="Alice",orderDate=2023-10-27 14:30)` to accurately adapt to the rules defined in the annotations. This is done at runtime without modifying the `Order` class's source code or recompiling, and the generated bytecode file is saved to ensure consistent behavior in subsequent calls.

[0087] The annotation processing method provided by this invention significantly reduces the risk of errors caused by manual intervention by dynamically intercepting and processing class-level and field-level annotations when the source code is run directly without compilation. By rewriting the source code in real time and generating a third-party bytecode file, it effectively ensures the consistency between runtime annotation configuration and source code definition, avoiding configuration deviations caused by direct execution. At the same time, this implementation method further enhances the flexibility of the development and testing phases, facilitating rapid iterative verification by developers without additional compilation steps, thereby greatly improving development efficiency and overall system reliability.

[0088] This embodiment also provides an annotation processing apparatus for implementing the above embodiments and preferred embodiments; details already described will not be repeated. As used below, the term "module" can refer to a combination of software and / or hardware that performs a predetermined function. Although the apparatus described in the following embodiments is preferably implemented in software, hardware implementation, or a combination of software and hardware, is also possible and contemplated.

[0089] This embodiment provides an annotation processing device, such as... Figure 4 As shown, it includes: The annotation acquisition module 401 is used to acquire class-level annotations added by the user to the target class in the source code. Class-level annotations are used to define and configure the class attributes of the target class. The annotation processing module 402 is used to rewrite the source code of the target class based on the class-level annotations when a source code compilation instruction is received, and compile it to generate the first bytecode file corresponding to the class-level annotations.

[0090] In some optional implementations, the annotation acquisition module 401 includes: The class request and response unit is used to respond to user requests for class annotations of the target class; The class format acquisition unit is used to obtain the output format type and field inclusion rules of the source code of the target class based on the class annotation request. The class parameter retrieval unit is used to define and configure the class attributes of the target class based on the output format type and field inclusion rules, and obtain the class annotation configuration parameters; Class-level annotation units are used to generate and insert class-level annotations into the source code based on class annotation configuration parameters.

[0091] In some alternative implementations, the annotation processing module 402 includes: The first source code rewriting unit is used to rewrite the source code of the target class based on class-level annotations when a source code compilation instruction is received, so as to obtain the first source code string. The first bytecode generation unit is used to compile the first source code string to generate the first bytecode file corresponding to the class-level annotation.

[0092] In some optional implementations, the annotation acquisition module 401 is also used to acquire field-level annotations added by the user to the fields of the target class in the source code, the field-level annotations being used to define and configure the field attributes of the target class; The annotation processing module 402 is also used to rewrite the source code of the target class based on the field-level annotations when a source code compilation instruction is received, and compile it to generate a second bytecode file corresponding to the field-level annotations.

[0093] In some optional implementations, the annotation acquisition module 401 further includes: The field request and response unit is used to respond to user requests for field annotations of the target class; The field format retrieval unit is used to retrieve the field aliases and field output formats of the target class based on the field annotation request. The field parameter retrieval unit is used to define and configure the field attributes of the target class based on the field alias and field output format, and obtain the field annotation configuration parameters; The field annotation unit is used to generate and insert field-level annotations into the source code based on the field annotation configuration parameters.

[0094] In some optional implementations, the annotation processing module 402 further includes: The second source code rewriting unit is used to rewrite the source code of the target class based on class-level annotations and field-level annotations when a source code compilation instruction is received, so as to obtain the second source code string. The second bytecode generation unit is used to compile the second source code string to generate a second bytecode file corresponding to the class-level annotation.

[0095] In some optional implementations, the annotation acquisition module 401 is also used to intercept class-level annotations and field-level annotations when the source code is run directly without being compiled, and the source code reaches the class-level annotations or field-level annotations of the target class. The annotation processing module 402 also rewrites the source code of the target class using interception-based class-level annotations and field-level annotations, and generates the corresponding third bytecode file.

[0096] The annotation processing apparatus provided in this embodiment of the invention can execute the annotation processing method provided in any embodiment of the invention, and has the corresponding functional modules and beneficial effects for executing the method. Further functional descriptions of the various modules and units described above are the same as in the corresponding embodiments described above, and will not be repeated here.

[0097] Figure 5 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention.

[0098] The following is a detailed reference. Figure 5 The diagram illustrates a structural schematic suitable for implementing an electronic device according to embodiments of the present invention. The electronic device may include a processor (e.g., a central processing unit, graphics processor, etc.) 501, which can perform various appropriate actions and processes according to a program stored in read-only memory (ROM) 502 or a program loaded from memory 508 into random access memory (RAM) 503. The RAM 503 also stores various programs and data required for the operation of the electronic device. The processor 501, ROM 502, and RAM 503 are interconnected via a bus 504. An input / output (I / O) interface 505 is also connected to the bus 504.

[0099] Typically, the following devices can be connected to I / O interface 505: input devices 506 including, for example, touchscreens, touchpads, keyboards, mice, cameras, microphones, accelerometers, gyroscopes, etc.; output devices 507 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; memory devices 508 including, for example, magnetic tapes, hard disks, etc.; and communication devices 509. Communication device 509 allows electronic devices to communicate wirelessly or wiredly with other devices to exchange data. Although Figure 5 Electronic devices with various devices are shown, but it should be understood that it is not required to implement or have all of the devices shown, and more or fewer devices may be implemented or have instead.

[0100] In particular, according to embodiments of the present invention, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of the present invention include a computer program product comprising a computer program carried on a non-transitory computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device 509, or installed from a memory 508, or installed from a ROM 502. When the computer program is executed by the processor 501, it performs the functions defined in the annotation processing method of the embodiments of the present invention.

[0101] Figure 5 The electronic device shown is merely an example and should not be construed as limiting the functionality and scope of use of the embodiments of the present invention.

[0102] This invention also provides a computer-readable storage medium. The methods described above according to embodiments of the invention can be implemented in hardware or firmware, or implemented as computer code that can be recorded on a storage medium, or implemented as computer code downloaded via a network and originally stored on a remote storage medium or a non-transitory machine-readable storage medium and then stored on a local storage medium. Thus, the methods described herein can be processed by software stored on a storage medium using a general-purpose computer, a dedicated processor, or programmable or dedicated hardware. The storage medium can be a magnetic disk, optical disk, read-only memory, random access memory, flash memory, hard disk, or solid-state drive, etc.; further, the storage medium can also include combinations of the above types of memory. It is understood that computers, processors, microprocessor controllers, or programmable hardware include storage components capable of storing or receiving software or computer code. When the software or computer code is accessed and executed by the computer, processor, or hardware, the annotation processing method shown in the above embodiments is implemented.

[0103] A portion of this invention can be applied as a computer program product, such as computer program instructions, which, when executed by a computer, can invoke or provide the methods and / or technical solutions according to the invention through the operation of the computer. Those skilled in the art will understand that the forms in which computer program instructions exist in a computer-readable medium include, but are not limited to, source files, executable files, installation package files, etc. Correspondingly, the ways in which computer program instructions are executed by a computer include, but are not limited to: the computer directly executing the instructions, or the computer compiling the instructions and then executing the corresponding compiled program, or the computer reading and executing the instructions, or the computer reading and installing the instructions and then executing the corresponding installed program. Here, the computer-readable medium can be any available computer-readable storage medium or communication medium accessible to a computer.

[0104] Although embodiments of the invention have been described in conjunction with the accompanying drawings, those skilled in the art can make various modifications and variations without departing from the spirit and scope of the invention, and such modifications and variations all fall within the scope defined by the appended claims.< / fieldinfo>

Claims

1. An annotation processing method, characterized in that, The method includes: Obtain the class-level annotations added by the user for the target class in the source code, wherein the class-level annotations are used to define and configure the class attributes of the target class; When a source code compilation instruction is received, the source code of the target class is rewritten based on the class-level annotation, and the first bytecode file corresponding to the class-level annotation is generated.

2. The method according to claim 1, characterized in that, Add the class-level annotation to the target class, including: Respond to the user's request for class annotations for the target class; Based on the class annotation request, obtain the output format type and field inclusion rules of the source code of the target class; Based on the output format type and field inclusion rules, the class attributes of the target class are defined and configured to obtain class annotation configuration parameters; The class-level annotations are generated and inserted into the source code based on the class annotation configuration parameters.

3. The method according to claim 1 or 2, characterized in that, When a source code compilation instruction is received, rewriting the source code of the target class based on the class-level annotation and compiling it to generate a first bytecode file corresponding to the class-level annotation includes: When a source code compilation instruction is received, the source code of the target class is rewritten based on the class-level annotation to obtain the first source code string; The first source code string is compiled to generate the first bytecode file corresponding to the class-level annotation.

4. The method according to claim 1, characterized in that, The method further includes: Obtain the field-level annotations added by the user to the fields of the target class in the source code, wherein the field-level annotations are used to define and configure the field attributes of the target class; When the source code compilation instruction is received, the source code of the target class is rewritten based on the field-level annotation, and a second bytecode file corresponding to the field-level annotation is generated.

5. The method according to claim 4, characterized in that, Adding the field-level annotation to the target class includes: Respond to the user's request for field annotations of the target class; Based on the field annotation request, obtain the field aliases and field output formats of the target class; Based on the field alias and the field output format, define and configure the field attributes of the target class to obtain the field annotation configuration parameters; The field-level annotations are generated and inserted into the source code according to the field annotation configuration parameters.

6. The method according to claim 4, characterized in that, When the source code compilation instruction is received, the process of rewriting the source code of the target class based on the field-level annotation and compiling it to generate a second bytecode file corresponding to the field-level annotation includes: When a source code compilation instruction is received, the source code of the target class is rewritten based on the class-level annotations and the field-level annotations to obtain a second source code string; The second source code string is compiled to generate a second bytecode file corresponding to the class-level annotation.

7. The method according to claim 1, characterized in that, The method further includes: When the source code is run directly without being compiled, the class-level annotation and the field-level annotation of the target class are intercepted when the source code runs to the class-level annotation or the field-level annotation. The source code of the target class is rewritten based on the intercepted class-level annotations and field-level annotations, and the corresponding third bytecode file is generated.

8. An annotation processing apparatus, characterized in that, The device includes: The annotation acquisition module is used to acquire class-level annotations added by the user to the target class in the source code. The class-level annotations are used to define and configure the class attributes of the target class. The annotation processing module is used to rewrite the source code of the target class based on the class-level annotation when a source code compilation instruction is received, and compile it to generate a first bytecode file corresponding to the class-level annotation.

9. An electronic device, characterized in that, include: A memory and a processor, the memory and the processor being communicatively connected to each other, the memory storing computer instructions, the processor executing the computer instructions to perform the method of any one of claims 1 to 7.

10. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer instructions for causing the computer to perform the method of any one of claims 1 to 7.