Skip to content

Instantly share code, notes, and snippets.

@spacether
Last active December 5, 2023 05:43
Show Gist options
  • Select an option

  • Save spacether/7235c6d9a0d39a98d3eb5a379d8245fa to your computer and use it in GitHub Desktop.

Select an option

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
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