How to use Assertions in Java

Assertion.java

package com.test;
public class Assertion {

public static boolean isassert = true;

private static void printStack(String why) {
Throwable t = new Throwable(why);
t.printStackTrace();
System.exit(1);
}

public static void assert1(boolean expression, String why) {
if (isassert && !expression) {
printStack(why);
}
}
}

LoaderAssertions.java

package com.test;

public class LoaderAssertions {
public static void main(String[] args) {

ClassLoader loader= ClassLoader.getSystemClassLoader();

loader.setDefaultAssertionStatus(true);

new Loaded().go();
}
}

class Loaded {
public void go() {
assert false: "Testing";
}
}



Test1.java

package com.test;

import java.io.IOException;

public class Test1 {

int age1 = 11;

public static void main(String argv[]) throws IOException {

ClassLoader loader = ClassLoader.getSystemClassLoader();

loader.setDefaultAssertionStatus(true);
//loader.setClassAssertionStatus("com.test.Test1", true);
Test1 test=new Test1();
assert test.age1 >= 18 : "You are too young to vote";

}
}

Test2.java

package com.test;

import java.io.IOException;

public class Test2 {
public static void main(String argv[]) throws IOException {

int age1 =19;

assert age1 >=18:"You are too young to vote";

System.out.println("you are eligible to vote");

}
}

No comments: