Skip to content

Method: ReflectionUtils()

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jopa.utils;
19:
20: import cz.cvut.kbss.jopa.exception.InstantiationException;
21:
22: import java.lang.reflect.InvocationTargetException;
23:
24: /**
25: * Utility functions using Java Reflection API.
26: */
27: public class ReflectionUtils {
28:
29: private ReflectionUtils() {
30: throw new AssertionError();
31: }
32:
33: /**
34: * Creates a new instance of the specified class using the default no-arg constructor.
35: * <p>
36: * Note that it is expected that the no-arg constructor exists and is publicly accessible.
37: *
38: * @param cls Class to instantiate
39: * @param <T> Type
40: * @return New instance of class {@code cls}
41: * @throws InstantiationException When no-arg constructor does not exist or is not accessible
42: */
43: public static <T> T instantiateUsingDefaultConstructor(Class<T> cls) {
44: // The main purpose of this method is to wrap object instantiation so that the deprecated Class.newInstance
45: // calls can be replaced after migrating to newer Java version
46: try {
47: return cls.getDeclaredConstructor().newInstance();
48: } catch (java.lang.InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
49: throw new InstantiationException(e);
50: }
51: }
52: }