View Javadoc
1   /*
2    * SPDX-License-Identifier: Apache-2.0
3    * See LICENSE file for details.
4    *
5    * Copyright 2012-2026 hazendaz
6    *
7    * Portions of initial baseline code (getter/setter test) by Rob Dawson (CodeBox)
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   * The Constructor Instance.
18   */
19  public final class ConstructorInstance {
20  
21      /**
22       * Prevent Instantiation of a new constructor instance.
23       */
24      private ConstructorInstance() {
25          // Prevent Instantiation
26      }
27  
28      /**
29       * New instance.
30       *
31       * @param constructor
32       *            the instance
33       *
34       * @return the Object
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       * Constructor inaccessibility test.
49       *
50       * @param clazz
51       *            the clazz
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          // Make accessible 'true' in order to test following assert.
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          // Set accessible back to 'false'
64          ctor.setAccessible(false);
65      }
66  }