Here you can find the source of invokeConstructor(String className, Object... arguments)
Parameter | Description |
---|---|
className | a parameter |
arguments | a parameter |
public static Object invokeConstructor(String className, Object... arguments)
//package com.java2s; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class Main { /**// w ww.j a v a 2s .c o m * Returns an instantiation of the class specified by the input {@link String} using the * arguments provided. * * @param className * @param arguments * @return */ public static Object invokeConstructor(String className, Object... arguments) { try { Class<?> cls = Class.forName(className); Class<?>[] parameterTypes = new Class<?>[arguments.length]; int i = 0; for (Object argument : arguments) parameterTypes[i++] = argument.getClass(); Constructor<?> constructor = cls.getConstructor(parameterTypes); if (!constructor.isAccessible()) constructor.setAccessible(true); return constructor.newInstance(arguments); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SecurityException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } }