Last active
December 5, 2023 05:43
-
-
Save spacether/7235c6d9a0d39a98d3eb5a379d8245fa to your computer and use it in GitHub Desktop.
Java classes that allow type safe extraction of a value that is String or Number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.openapijsonschematools.client.schemas; | |
| public class RootClass { | |
| public static abstract class StringNumberType { | |
| } | |
| public static final class StringType extends StringNumberType { | |
| } | |
| public static final class NumberType extends StringNumberType { | |
| } | |
| public enum TypeToXType { | |
| STRING(new StringType()), | |
| NUMBER(new NumberType()); | |
| public final StringNumberType type; | |
| private TypeToXType(StringNumberType type) { | |
| this.type = type; | |
| } | |
| } | |
| public class SomePayload { | |
| public String someProp(StringType xType) { | |
| return "val"; | |
| } | |
| public Number someProp(NumberType xType) { | |
| return 1; | |
| } | |
| } | |
| public Void methodDemonstratingExhaustiveTypeHandling() { | |
| SomePayload payload = new SomePayload(); | |
| for (TypeToXType typeToXType: TypeToXType.values()) { | |
| switch (typeToXType) { | |
| case NUMBER: | |
| Number numberVal = payload.someProp((NumberType) typeToXType.type); | |
| break; | |
| case STRING: | |
| String stringVal = payload.someProp((StringType) typeToXType.type); | |
| break; | |
| } | |
| } | |
| return null; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment