[BAEL-5788] Accessing Private Constructor

This commit is contained in:
Stef Serban-Cristian 2023-02-13 23:42:35 +02:00
parent 3af60557bd
commit cb308a89e8
2 changed files with 25 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package com.baeldung.reflection;
public class PrivateConstructorClass {
private PrivateConstructorClass() {
System.out.println("Used the private constructor!");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.reflection;
import java.lang.reflect.Constructor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class PrivateConstructorUnitTest {
@Test
public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception {
Constructor<PrivateConstructorClass> pcc = PrivateConstructorClass.class.getDeclaredConstructor();
pcc.setAccessible(true);
PrivateConstructorClass privateConstructorInstance = pcc.newInstance();
Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass);
}
}