Create a new instance for the given klass. Runtime exceptions thrown from the constructor are rethrown, all other exceptions generated from the reflective call are wrapped into a java.lang.IllegalArgumentException and rethrown. @param klass desired class to instantiate @return the n
(Class<T> klass)
| 44 | * a runtime exception |
| 45 | */ |
| 46 | public static <T> T newInstance(Class<T> klass) { |
| 47 | try { |
| 48 | return klass.getDeclaredConstructor().newInstance(); |
| 49 | } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException e) { |
| 50 | String msg = "Can't create an instance of " + klass |
| 51 | + ", requires a public no-arg constructor: " + e; |
| 52 | throw new IllegalArgumentException(msg, e); |
| 53 | } catch (InvocationTargetException e) { |
| 54 | if (e.getCause() instanceof RuntimeException) { |
| 55 | throw (RuntimeException) e.getCause(); |
| 56 | } else { |
| 57 | String msg = "Can't create an instance of " + klass |
| 58 | + ", requires a public no-arg constructor: " + e; |
| 59 | throw new IllegalArgumentException(msg, e); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
no outgoing calls