MCPcopy Create free account
hub / github.com/apache/fory / generate_union_class

Method generate_union_class

compiler/fory_compiler/generators/java.py:766–950  ·  view source on GitHub ↗

Generate a Java union class.

(
        self,
        union: Union,
        indent: int = 0,
        nested: bool = False,
        parent_stack: Optional[List[Message]] = None,
    )

Source from the content-addressed store, hash-verified

764 return lines
765
766 def generate_union_class(
767 self,
768 union: Union,
769 indent: int = 0,
770 nested: bool = False,
771 parent_stack: Optional[List[Message]] = None,
772 ) -> List[str]:
773 """Generate a Java union class."""
774 lines: List[str] = []
775 ind = " " * indent
776 class_prefix = "public static final class" if nested else "public final class"
777 case_enum = f"{union.name}Case"
778
779 comment = self.format_type_id_comment(union, f"{ind}//")
780 if comment:
781 lines.append(comment)
782 lines.append(f"{ind}{class_prefix} {union.name} extends Union {{")
783 lines.append(f"{ind} public enum {case_enum} {{")
784
785 for i, field in enumerate(union.fields):
786 comma = "," if i < len(union.fields) - 1 else ";"
787 case_name = self.to_upper_snake_case(field.name)
788 lines.append(f"{ind} {case_name}({field.number}){comma}")
789
790 lines.append(f"{ind} public final int id;")
791 lines.append(f"{ind} {case_enum}(int id) {{")
792 lines.append(f"{ind} this.id = id;")
793 lines.append(f"{ind} }}")
794 lines.append(f"{ind} }}")
795 lines.append("")
796
797 lines.append(f"{ind} private static int resolveTypeId(int caseId) {{")
798 lines.append(f"{ind} switch (caseId) {{")
799 for field in union.fields:
800 type_id_expr = self.get_union_case_type_id_expr(field, parent_stack)
801 lines.append(f"{ind} case {field.number}:")
802 lines.append(f"{ind} return {type_id_expr};")
803 lines.append(f"{ind} default:")
804 lines.append(
805 f'{ind} throw new IllegalStateException("Unknown {union.name} case id: " + caseId);'
806 )
807 lines.append(f"{ind} }}")
808 lines.append(f"{ind} }}")
809 lines.append("")
810
811 lines.append(f"{ind} private {union.name}(int caseId, Object v) {{")
812 lines.append(f"{ind} super(caseId, v, resolveTypeId(caseId));")
813 lines.append(f"{ind} if (v == null) {{")
814 lines.append(f"{ind} throw new NullPointerException();")
815 lines.append(f"{ind} }}")
816 lines.append(f"{ind} get{union.name}Case();")
817 lines.append(f"{ind} }}")
818 lines.append("")
819
820 for field in union.fields:
821 case_name = self.to_pascal_case(field.name)
822 case_enum_name = self.to_upper_snake_case(field.name)
823 case_type = self.get_union_case_type(field, parent_stack)

Callers 4

generate_union_fileMethod · 0.95
generate_message_fileMethod · 0.95

Calls 13

get_union_case_typeMethod · 0.95
java_arrayMethod · 0.95
anyFunction · 0.85
to_upper_snake_caseMethod · 0.80
to_pascal_caseMethod · 0.80

Tested by

no test coverage detected