1
2
3
4
5
6
7
8
9 package com.codebox.instance;
10
11 import java.lang.reflect.Constructor;
12 import java.lang.reflect.InvocationTargetException;
13
14 import org.junit.jupiter.api.Assertions;
15
16
17
18
19 public final class ConstructorInstance {
20
21
22
23
24 private ConstructorInstance() {
25
26 }
27
28
29
30
31
32
33
34
35
36 public static Object newInstance(final Constructor<?> constructor) {
37 try {
38 return constructor.newInstance();
39 } catch (final InstantiationException | IllegalAccessException | InvocationTargetException e) {
40 Assertions.fail(
41 String.format("An exception was thrown while testing the constructor (new instance) '%s': '%s'",
42 constructor.getName(), e.toString()));
43 }
44 return null;
45 }
46
47
48
49
50
51
52
53 public static void inaccessible(final Class<?> clazz) {
54 final Constructor<?>[] ctors = clazz.getDeclaredConstructors();
55 Assertions.assertEquals(1, ctors.length, "Utility class should only have one constructor");
56 final Constructor<?> ctor = ctors[0];
57 Assertions.assertFalse(ctor.canAccess(null), "Utility class constructor should be inaccessible");
58
59 ctor.setAccessible(true);
60 final Object object = ConstructorInstance.newInstance(ctor);
61 Assertions.assertEquals(clazz, object == null ? "null" : object.getClass(),
62 "You would expect the constructor to return the expected type");
63
64 ctor.setAccessible(false);
65 }
66 }