short answer
you cannot (using only JDK classes)
long answer
try:
public interface Constant { int value(); } public static Class<? extends Constant> classBuilder(final int value) { return new Constant() { @Override public int value() { return value; } @Override public String toString() { return String.valueOf(value); } }.getClass(); }
create two new classes of "parametric" classes:
Class<? extends Constant> oneClass = createConstantClass(1); Class<? extends Constant> twoClass = createConstantClass(2);
however, you cannot instantiate these classes:
Constant one = oneClass.newInstance(); // <--- throws InstantiationException Constant two = twoClass.newInstance(); // <--- ditto
it will fail at runtime since there is only one instance for each anonymous class .
However, you can create dynamic classes at runtime using bytecode manipulation libraries such as ASM . Another approach is to use dynamic proxies , but this approach is a drawback, which allows you to proxy only interface methods (so you need a Java interface).
source share