Skip to content

Instantly share code, notes, and snippets.

@stefanofago73
Created December 11, 2025 21:22
Show Gist options
  • Select an option

  • Save stefanofago73/14b4b74dc0875c504dfbfd700feaa1c9 to your computer and use it in GitHub Desktop.

Select an option

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