Skip to content

Commit 421bfc6

Browse files
committed
Added code examples for BAEL-4534
1 parent 719b713 commit 421bfc6

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.checkclassexistence;
2+
3+
import org.junit.Test;
4+
5+
public class CheckClassExistenceUnitTest {
6+
7+
public static class InitializingClass {
8+
static {
9+
if (true) //enable throwing of an exception in a static initialization block
10+
throw new RuntimeException();
11+
}
12+
}
13+
14+
@Test(expected = ClassNotFoundException.class) //thrown when class does not exist
15+
public void givenNonExistingClass_whenUsingForName_classNotFound() throws ClassNotFoundException {
16+
Class.forName("class.that.does.not.exist");
17+
}
18+
19+
@Test
20+
public void givenExistingClass_whenUsingForName_noException() throws ClassNotFoundException {
21+
Class.forName("java.lang.String");
22+
}
23+
24+
@Test(expected = ExceptionInInitializerError.class) //thrown when exception occurs inside of a static initialization block
25+
public void givenInitializingClass_whenUsingForName_initializationError() throws ClassNotFoundException {
26+
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass");
27+
}
28+
29+
@Test
30+
public void givenInitializingClass_whenUsingForNameWithoutInitialization_noException() throws ClassNotFoundException {
31+
Class.forName("com.baeldung.checkclassexistence.CheckClassExistenceUnitTest$InitializingClass", false, getClass().getClassLoader());
32+
}
33+
}

0 commit comments

Comments
 (0)