Merge pull request #13475 from StefSC/BAEL-5788-Private-Constructor

[BAEL-5788] Accessing Private Constructor
This commit is contained in:
davidmartinezbarua 2023-02-17 21:03:32 -03:00 committed by GitHub
commit db2d8069e3
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);
}
}