Enabling and Disabling Assertions
By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions.
To enable assertions at various granularities, use the
-enableassertions
, or-ea
, switch. To disable assertions at various granularities, use the-disableassertions
, or-da
, switch. You specify the granularity with the arguments that you provide to the switch:
Assertion for constructor variables [closed]
-
02-10-2022 - |
Pergunta
I am trying use assertions on a constructor in a abstract class, the String variable thename cannot be null or empty and the int variable thesize cannot be negative or zero here is how I tried to do it but the test case I was provided does not pass. How would I assert the conditions for the constructor?
public abstract class AbstractItem implements Item{
private int size;
private String name;
public AbstractItem(String thename, int thesize){
assert thename != null;
assert thename.length() > 0;
assert thesize > 0;
name = thename;
size = thesize;
}
public final int getSize(){
return size;
}
public String toString(){
return name;
}
}
Solução
Outras dicas
If you use Spring, you could also use their Assert, it comes with handy error messages too, so you can have a humanly readable error for why an assertion failed. Here is a snippet from Spring's ACL library, if sid is null, you'll get a nice error message saying so.
public Long createOrRetrieveSidPrimaryKey(Sid sid, boolean allowCreate) {
Assert.notNull(sid, "Sid required");
// more code here ....
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow