10 years ago

10 years ago

10 years ago
Force passing class arguments to the constructor using an interfaceForce passing final arguments to constructor using an interface

10 years ago

public static final class Lenght5 implements Lenght { @Override public final int getLenght() { return 5; } } public static final class Lenght8 implements Lenght { @Override public int getLenght() { return 8; } } public static interface Lenght { int getLenght(); } public static class ID<T extends Lenght> { public ID(final T lenght, final String str) { if (str.length() > lenght.getLenght()) { throw new IllegalArgumentException("ID to long!"); } } } public static void main(final String[] args) { final ID<Lenght5> id1 = new ID<>(new Lenght5(), "12345");// works final ID<Lenght5> id2 = new ID<>(new Lenght5(), "123456");// throws Exception }You use an interface that has a getter-method for the non-type-argument. And then force to pass a derived instance of the interface to the constructor of the class, that should've the argument.

10 years ago

10 years ago

undefinedurl nextprice drop