List of usage examples for java.lang.reflect Constructor newInstance
@CallerSensitive @ForceInline public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
From source file:demo.config.PropertyConverter.java
/** * Tries to convert the specified object into a number object. This method * is used by the conversion methods for number types. Note that the return * value is not in always of the specified target class, but only if a new * object has to be created./*from w ww . j a va2s .c om*/ * * @param value * the value to be converted (must not be <b>null</b>) * @param targetClass * the target class of the conversion (must be derived from * {@code java.lang.Number}) * @return the converted number * @throws ConversionException * if the object cannot be converted */ static Number toNumber(Object value, Class<?> targetClass) throws ConversionException { if (value instanceof Number) { return (Number) value; } else { String str = value.toString(); if (str.startsWith(HEX_PREFIX)) { try { return new BigInteger(str.substring(HEX_PREFIX.length()), HEX_RADIX); } catch (NumberFormatException nex) { throw new ConversionException( "Could not convert " + str + " to " + targetClass.getName() + "! Invalid hex number.", nex); } } if (str.startsWith(BIN_PREFIX)) { try { return new BigInteger(str.substring(BIN_PREFIX.length()), BIN_RADIX); } catch (NumberFormatException nex) { throw new ConversionException("Could not convert " + str + " to " + targetClass.getName() + "! Invalid binary number.", nex); } } try { Constructor<?> constr = targetClass.getConstructor(CONSTR_ARGS); return (Number) constr.newInstance(new Object[] { str }); } catch (InvocationTargetException itex) { throw new ConversionException("Could not convert " + str + " to " + targetClass.getName(), itex.getTargetException()); } catch (Exception ex) { // Treat all possible exceptions the same way throw new ConversionException( "Conversion error when trying to convert " + str + " to " + targetClass.getName(), ex); } } }
From source file:com.asual.summer.core.util.ClassUtils.java
public static Object newInstance(String clazz, Object... parameters) throws SecurityException, ClassNotFoundException { Class<?>[] classParameters = new Class[parameters == null ? 0 : parameters.length]; for (int i = 0; i < classParameters.length; i++) { classParameters[i] = parameters[i].getClass(); }/*from w w w.j a v a2s. co m*/ Object instance = null; try { instance = Class.forName(clazz).getConstructor(classParameters) .newInstance(parameters == null ? new Object[] {} : parameters.length); } catch (Exception e) { Constructor<?>[] constructors = Class.forName(clazz).getConstructors(); for (Constructor<?> constructor : constructors) { Class<?>[] types = constructor.getParameterTypes(); if (types.length == parameters.length) { Object[] params = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { if (types[i] == boolean.class || types[i] == Boolean.class) { params[i] = Boolean.valueOf(parameters[i].toString()); } else if (types[i] == int.class || types[i] == Integer.class) { params[i] = Integer.valueOf(parameters[i].toString()); } else { params[i] = types[i].cast(parameters[i]); } } try { instance = constructor.newInstance(params); break; } catch (Exception ex) { continue; } } } } return instance; }
From source file:com.helpinput.utils.Utils.java
public static <T> T constructorNewInstance(Class<T> classType, Object... agrs) { if (agrs == null) { try {/*from ww w .j a v a 2s. co m*/ return classType.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } Constructor<?> cst = findConstructor(classType, agrs); if (cst != null) { try { @SuppressWarnings("unchecked") T instance = (T) cst.newInstance(agrs); return instance; } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; }
From source file:demo.config.PropertyConverter.java
/** * Convert the specified value into an email address. * //from w ww.j a v a 2 s . com * @param value * the value to convert * @return the converted value * @throws ConversionException * thrown if the value cannot be converted to an email address * * @since 1.5 */ static Object toInternetAddress(Object value) throws ConversionException { if (value.getClass().getName().equals(INTERNET_ADDRESS_CLASSNAME)) { return value; } else if (value instanceof String) { try { Constructor<?> ctor = Class.forName(INTERNET_ADDRESS_CLASSNAME) .getConstructor(new Class[] { String.class }); return ctor.newInstance(new Object[] { value }); } catch (Exception e) { throw new ConversionException("The value " + value + " can't be converted to a InternetAddress", e); } } else { throw new ConversionException("The value " + value + " can't be converted to a InternetAddress"); } }
From source file:com.helpinput.core.Utils.java
public static <T> T newInstance(Class<T> classType, Object... args) { if (!hasLength(args)) { try {/*from w ww. j av a2 s . c o m*/ return classType.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; } Constructor<?> cst = findConstructor(classType, args); if (cst != null) { try { @SuppressWarnings("unchecked") T instance = (T) cst.newInstance(args); return instance; } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return null; }
From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java
private static View getViewForName(Context context, String name) { try {/*w ww . j ava 2s . co m*/ if (!name.contains(".")) { name = "android.widget." + name; } Class<?> clazz = Class.forName(name); Constructor<?> constructor = clazz.getConstructor(Context.class); return (View) constructor.newInstance(context); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
From source file:net.sf.ehcache.config.BeanHandler.java
/** * Creates a child object.//from ww w .j ava2s . c o m */ private static Object createInstance(Object parent, Class childClass) throws Exception { final Constructor[] constructors = childClass.getConstructors(); ArrayList candidates = new ArrayList(); for (int i = 0; i < constructors.length; i++) { final Constructor constructor = constructors[i]; final Class[] params = constructor.getParameterTypes(); if (params.length == 0) { candidates.add(constructor); } else if (params.length == 1 && params[0].isInstance(parent)) { candidates.add(constructor); } } switch (candidates.size()) { case 0: throw new Exception("No constructor for class " + childClass.getName()); case 1: break; default: throw new Exception("Multiple constructors for class " + childClass.getName()); } final Constructor constructor = (Constructor) candidates.remove(0); if (constructor.getParameterTypes().length == 0) { return constructor.newInstance(new Object[] {}); } else { return constructor.newInstance(new Object[] { parent }); } }
From source file:dk.netarkivet.archive.webinterface.BatchGUI.java
/** * Method for executing a batchjob./*from w ww. j a v a2 s.com*/ * * @param context The page context containing the needed information for executing the batchjob. */ @SuppressWarnings("rawtypes") public static void execute(PageContext context) { try { ServletRequest request = context.getRequest(); // get parameters String filetype = request.getParameter(Constants.FILETYPE_PARAMETER); String jobId = request.getParameter(Constants.JOB_ID_PARAMETER); String jobName = request.getParameter(Constants.BATCHJOB_PARAMETER); String repName = request.getParameter(Constants.REPLICA_PARAMETER); FileBatchJob batchjob; // Retrieve the list of arguments. List<String> args = new ArrayList<String>(); String arg; Integer i = 1; // retrieve the constructor to find out how many arguments Class c = getBatchClass(jobName); Constructor con = findStringConstructor(c); // retrieve the arguments and put them into the list. while (i <= con.getParameterTypes().length) { arg = request.getParameter("arg" + i.toString()); if (arg != null) { args.add(arg); } else { log.warn("Should contain argument number " + i + ", but " + "found a null instead, indicating missing " + "argument. Use empty string instead."); args.add(""); } i++; } File jarfile = getJarFile(jobName); if (jarfile == null) { // get the constructor and instantiate it. Constructor construct = findStringConstructor(getBatchClass(jobName)); batchjob = (FileBatchJob) construct.newInstance(args.toArray()); } else { batchjob = new LoadableJarBatchJob(jobName, args, jarfile); } // get the regular expression. String regex = jobId + "-"; if (filetype.equals(BatchFileType.Metadata.toString())) { regex += Constants.REGEX_METADATA; } else if (filetype.equals(BatchFileType.Content.toString())) { // TODO fix this 'content' regex. (NAS-1394) regex += Constants.REGEX_CONTENT; } else { regex += Constants.REGEX_ALL; } // validate the regular expression (throws exception if wrong). Pattern.compile(regex); Replica rep = Replica.getReplicaFromName(repName); new BatchExecuter(batchjob, regex, rep).start(); JspWriter out = context.getOut(); out.write("Executing batchjob with the following parameters. " + "<br/>\n"); out.write("BatchJob name: " + jobName + "<br/>\n"); out.write("Replica: " + rep.getName() + "<br/>\n"); out.write("Regular expression: " + regex + "<br/>\n"); } catch (Exception e) { throw new IOFailure("Could not instantiate the batchjob.", e); } }
From source file:br.com.binarti.simplesearchexpr.converter.NumberSearchDataConverter.java
@SuppressWarnings("rawtypes") @Override/*from w w w .ja va 2 s .c o m*/ protected Object asSingleObject(SimpleSearchExpressionField field, String value, Map<String, Object> params, Class<?> targetType) { if (value == null) return null; if (targetType.isPrimitive()) { targetType = ClassUtils.primitiveToWrapper(targetType); } try { Constructor constructor = targetType.getConstructor(String.class); return constructor.newInstance(value.trim()); } catch (Exception e) { throw new SimpleSearchDataConverterException( "Error converter " + value + " to " + targetType.getClass()); } }
From source file:com.sequenceiq.ambari.shell.converter.AbstractConverter.java
@Override public T convertFromText(String value, Class<?> clazz, String optionContext) { try {// w w w.j a va2s .c o m Constructor<?> constructor = clazz.getDeclaredConstructor(String.class); return (T) constructor.newInstance(value); } catch (Exception e) { return null; } }