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