View Javadoc
1   /*
2    * JavaBean Tester (https://github.com/hazendaz/javabean-tester)
3    *
4    * Copyright 2012-2023 Hazendaz.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of The Apache Software License,
8    * Version 2.0 which accompanies this distribution, and is available at
9    * http://www.apache.org/licenses/LICENSE-2.0.txt
10   *
11   * Contributors:
12   *     CodeBox (Rob Dawson).
13   *     Hazendaz (Jeremy Landis).
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   * The Constructor Instance.
24   */
25  public final class ConstructorInstance {
26  
27      /**
28       * Prevent Instantiation of a new constructor instance.
29       */
30      private ConstructorInstance() {
31          // Prevent Instantiation
32      }
33  
34      /**
35       * New instance.
36       *
37       * @param constructor
38       *            the instance
39       *
40       * @return the Object
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       * Constructor inaccessibility test.
55       *
56       * @param clazz
57       *            the clazz
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          // Make accessible 'true' in order to test following assert.
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          // Set accessible back to 'false'
70          ctor.setAccessible(false);
71      }
72  }