Created
December 11, 2025 21:22
-
-
Save stefanofago73/14b4b74dc0875c504dfbfd700feaa1c9 to your computer and use it in GitHub Desktop.
This is an example of using var-args, and their definition by the Java compiler as pre-allocated arrays, to simulate in a simple way what is obtained with the Super Type Tokens pattern. Ugly and Raw but... funny enough!
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
| // ----- ELEMENTS TO DEMONSTRATE THE USAGE | |
| public interface Tool { | |
| void use(); | |
| } | |
| public record Tool1() implements Tool{ | |
| public void use() { | |
| System.out.println("tool1"); | |
| } | |
| } | |
| public record Tool2() implements Tool{ | |
| public void use() { | |
| System.out.println("tool2"); | |
| } | |
| } | |
| // ---- DEMO CLASS | |
| public final class Demo{ | |
| public static void main(String[] args) { | |
| var tmp = GenericTokens.two(new GenericToken<Tool1>(), new GenericToken<Tool2>()); | |
| System.out.printf("%s - %s %n",tmp[0],tmp[1]); | |
| tmp = GenericTokens.three(new GenericToken<Tool1>(), new GenericToken<Tool2>(),new GenericToken<Tool>()); | |
| System.out.printf("%s - %s - %s %n",tmp[0],tmp[1],tmp[2]); | |
| } | |
| } | |
| // ---- THE FRAMEWORK CLASSES | |
| public final class GenericToken<U>{ | |
| private Class<U> clazz; | |
| @SafeVarargs | |
| public GenericToken(U ... ignore) { | |
| @SuppressWarnings("unchecked") | |
| Class<U> tmp = (Class<U>) ignore.getClass().getComponentType(); | |
| clazz = tmp; | |
| } | |
| public final Class<U> token(){ | |
| return clazz; | |
| } | |
| } | |
| public final class GenericTokens { | |
| private GenericTokens() { | |
| throw new IllegalStateException("instantiation not allowed!"); | |
| } | |
| public static <U,R> Class<?>[] two(GenericToken<U> u, | |
| GenericToken<R> r){ | |
| return new Class<?>[] {u.token(),r.token()}; | |
| } | |
| public static <U,R,S> Class<?>[] three(GenericToken<U> u, | |
| GenericToken<R> r, | |
| GenericToken<S> s){ | |
| return new Class<?>[] {u.token(),r.token(),s.token()}; | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment