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:com.inmobi.grill.server.metastore.JAXBUtils.java
public static Storage storageFromXStorage(XStorage xs) { if (xs == null) { return null; }//from ww w . ja v a 2s .co m Storage storage = null; try { Class<?> clazz = Class.forName(xs.getClassname()); Constructor<?> constructor = clazz.getConstructor(String.class); storage = (Storage) constructor.newInstance(new Object[] { xs.getName() }); storage.addProperties(mapFromXProperties(xs.getProperties())); return storage; } catch (Exception e) { throw new WebApplicationException( "Could not create storage class" + xs.getClassname() + "with name:" + xs.getName(), e); } }
From source file:cascading.util.Util.java
public static Object createProtectedObject(Class type, Object[] parameters, Class[] parameterTypes) { try {//from ww w . java2 s . c om Constructor constructor = type.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor.newInstance(parameters); } catch (Exception exception) { exception.printStackTrace(); throw new FlowException("unable to instantiate type: " + type.getName(), exception); } }
From source file:org.paxml.util.ReflectUtils.java
/** * Coerce object type./*from ww w. j a v a 2s. co m*/ * * @param <T> * the expected type * @param from * from object * @param expectedType * to object type * @return the to object */ public static <T> T coerceType(Object from, Class<? extends T> expectedType) { if (from == null) { return null; } Object targetValue = null; if (expectedType.isInstance(from)) { targetValue = from; } else if (expectedType.isEnum()) { for (Object e : expectedType.getEnumConstants()) { if (from.toString().equalsIgnoreCase(e.toString())) { targetValue = e; break; } } if (targetValue == null) { throw new PaxmlRuntimeException( "No enum named '" + from + "' is defined in class: " + expectedType); } } else if (List.class.equals(expectedType)) { targetValue = new ArrayList(); collect(from, (Collection) targetValue, true); } else if (Set.class.equals(expectedType)) { targetValue = new LinkedHashSet(); collect(from, (Collection) targetValue, true); } else if (isImplementingClass(expectedType, Collection.class, false)) { try { targetValue = expectedType.newInstance(); } catch (Exception e) { throw new PaxmlRuntimeException(e); } collect(from, (Collection) targetValue, true); } else if (Iterator.class.equals(expectedType)) { List list = new ArrayList(); collect(from, list, true); targetValue = list.iterator(); } else if (isImplementingClass(expectedType, Coerceable.class, false)) { try { Constructor c = expectedType.getConstructor(Object.class); targetValue = c.newInstance(from); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } else if (from instanceof Map) { return mapToBean((Map) from, expectedType); } else { targetValue = ConvertUtils.convert(from.toString(), expectedType); } return (T) targetValue; }
From source file:disko.DU.java
@SuppressWarnings("unchecked") public static <T> T cloneObject(T p, Mapping<Pair<Object, String>, Boolean> propertyFilter) throws Exception { if (p == null) return null; if (p instanceof Cloneable) { Method cloneMethod = p.getClass().getMethod("clone", (Class[]) null); if (cloneMethod != null) return (T) cloneMethod.invoke(p, (Object[]) null); } else if (p.getClass().isArray()) { Object[] A = (Object[]) p; Class<?> type = p.getClass(); Object[] ac = (Object[]) Array.newInstance(type.getComponentType(), A.length); for (int i = 0; i < A.length; i++) ac[i] = cloneObject(A[i], propertyFilter); return (T) ac; } else if (identityCloneClasses.contains(p.getClass())) return p; ////from www. j a va 2 s . c om // Need to implement cloning ourselves. We do this by copying bean properties. // Constructor<?> cons = null; try { cons = p.getClass().getConstructor((Class[]) null); } catch (Throwable t) { return p; } Object copy = cons.newInstance((Object[]) null); if (p instanceof Collection) { Collection<Object> cc = (Collection<Object>) copy; for (Object el : (Collection<?>) p) cc.add(cloneObject(el, propertyFilter)); } else if (p instanceof Map) { Map<Object, Object> cm = (Map<Object, Object>) copy; for (Object key : ((Map<Object, Object>) p).keySet()) cm.put(key, cloneObject(((Map<Object, Object>) p).get(key), propertyFilter)); } else { BeanInfo bean_info = Introspector.getBeanInfo(p.getClass()); PropertyDescriptor beanprops[] = bean_info.getPropertyDescriptors(); if (beanprops == null || beanprops.length == 0) copy = p; else for (PropertyDescriptor desc : beanprops) { Method rm = desc.getReadMethod(); Method wm = desc.getWriteMethod(); if (rm == null || wm == null) continue; Object value = rm.invoke(p, (Object[]) null); if (propertyFilter == null || propertyFilter.eval(new Pair<Object, String>(p, desc.getName()))) value = cloneObject(value, propertyFilter); wm.invoke(copy, new Object[] { value }); } } return (T) copy; }
From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java
/** * Navigates a XML document through an XPath and, for each encountered element, creates a specific WeatherBug data object (<i>Location</i>, * <i>Station</i>, and so on). Java reflection errors are silently ignored. * //from ww w . j a v a 2 s . com * @param elem * the XML element being accessed. * @param path * the XPath used to find specific sub-elements. * @param dataClass * the class of objects being instantiated (<i>Location</i>, <i>Station</i>, and so on). * @return a list of <i>dataClass</i> objects. */ public static <T> List<T> bind(Element elem, String path, Class<T> dataClass) { Constructor<T> constr; try { constr = dataClass.getConstructor(ELEM_CLASS_ARRAY); } catch (SecurityException e) { return Collections.emptyList(); } catch (NoSuchMethodException e) { return Collections.emptyList(); } List<T> resultList = new ArrayList<T>(); for (Object o : elem.selectNodes(path)) { Element item = (Element) o; try { resultList.add(constr.newInstance(item)); } catch (IllegalArgumentException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } } return resultList; }
From source file:BrowserLauncher.java
/** * Called by a static initializer to load any classes, fields, and methods required at runtime * to locate the user's web browser./*from w w w . j ava 2 s.co m*/ * @return <code>true</code> if all intialization succeeded * <code>false</code> if any portion of the initialization failed */ private static boolean loadClasses() { switch (jvm) { case MRJ_2_0: try { Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget"); Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils"); Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent"); Class aeClass = Class.forName("com.apple.MacOS.ae"); aeDescClass = Class.forName("com.apple.MacOS.AEDesc"); aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] { int.class }); appleEventConstructor = appleEventClass.getDeclaredConstructor( new Class[] { int.class, int.class, aeTargetClass, int.class, int.class }); aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class }); makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class[] { String.class }); putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass }); sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] {}); Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject"); keyDirectObject = (Integer) keyDirectObjectField.get(null); Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID"); kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null); Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID"); kAnyTransactionID = (Integer) anyTransactionIDField.get(null); } catch (ClassNotFoundException cnfe) { errorMessage = cnfe.getMessage(); return false; } catch (NoSuchMethodException nsme) { errorMessage = nsme.getMessage(); return false; } catch (NoSuchFieldException nsfe) { errorMessage = nsfe.getMessage(); return false; } catch (IllegalAccessException iae) { errorMessage = iae.getMessage(); return false; } break; case MRJ_2_1: try { mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType"); Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType"); kSystemFolderType = systemFolderField.get(null); findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass }); getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class }); getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class }); } catch (ClassNotFoundException cnfe) { errorMessage = cnfe.getMessage(); return false; } catch (NoSuchFieldException nsfe) { errorMessage = nsfe.getMessage(); return false; } catch (NoSuchMethodException nsme) { errorMessage = nsme.getMessage(); return false; } catch (SecurityException se) { errorMessage = se.getMessage(); return false; } catch (IllegalAccessException iae) { errorMessage = iae.getMessage(); return false; } break; case MRJ_3_0: try { Class linker = Class.forName("com.apple.mrj.jdirect.Linker"); Constructor constructor = linker.getConstructor(new Class[] { Class.class }); linkage = constructor.newInstance(new Object[] { BrowserLauncher.class }); } catch (ClassNotFoundException cnfe) { errorMessage = cnfe.getMessage(); return false; } catch (NoSuchMethodException nsme) { errorMessage = nsme.getMessage(); return false; } catch (InvocationTargetException ite) { errorMessage = ite.getMessage(); return false; } catch (InstantiationException ie) { errorMessage = ie.getMessage(); return false; } catch (IllegalAccessException iae) { errorMessage = iae.getMessage(); return false; } break; case MRJ_3_1: try { mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils"); openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class }); } catch (ClassNotFoundException cnfe) { errorMessage = cnfe.getMessage(); return false; } catch (NoSuchMethodException nsme) { errorMessage = nsme.getMessage(); return false; } break; default: break; } return true; }
From source file:de.tudarmstadt.ukp.dkpro.wsd.WSDUtils.java
/** * Read key-value pairs of the specified types from the specified columns of * a delimited text file into a Map./* ww w. j a va 2s . c o m*/ * * @param url * Location of the file to read * @param keyColumn * The index of the column giving the keys * @param keyClass * The class of the key * @param valueColumn * The index of the column giving the values * @param valueClass * The class of the value * @param delimiterRegex * A regular expression for the field delimiter * @return A map of keys to values * @throws IOException * @throws IllegalArgumentException */ public static <K, V> Map<K, V> readMap(final URL url, final int keyColumn, final Class<K> keyClass, final int valueColumn, final Class<V> valueClass, final String delimiterRegex) throws IOException, IllegalArgumentException { Map<K, V> map = new HashMap<K, V>(); InputStream is = url.openStream(); String content = IOUtils.toString(is, "UTF-8"); BufferedReader br = new BufferedReader(new StringReader(content)); Constructor<K> keyConstructor; Constructor<V> valueConstructor; try { keyConstructor = keyClass.getConstructor(String.class); valueConstructor = valueClass.getConstructor(String.class); } catch (Exception e) { throw new IllegalArgumentException(e); } String line; String[] lineParts; while ((line = br.readLine()) != null) { lineParts = line.split(delimiterRegex); K key; V value; try { key = keyConstructor.newInstance(lineParts[keyColumn - 1]); value = valueConstructor.newInstance(lineParts[valueColumn - 1]); } catch (Exception e) { throw new IllegalArgumentException(e); } map.put(key, value); } return map; }
From source file:de.tudarmstadt.ukp.dkpro.wsd.WSDUtils.java
/** * Read key-value pairs of the specified types from the specified columns of * a delimited text file into a Multimap. * * @param url//from w ww .ja va2 s . co m * Location of the file to read * @param keyColumn * The index of the column giving the keys * @param keyClass * The class of the key * @param valueColumn * The index of the column giving the values * @param valueClass * The class of the value * @param delimiterRegex * A regular expression for the field delimiter * @return A map of keys to values * @throws IOException * @throws IllegalArgumentException */ public static <K, V> Multimap<K, V> readMultimap(final URL url, final int keyColumn, final Class<K> keyClass, final int valueColumn, final Class<V> valueClass, final String delimiterRegex) throws IOException, IllegalArgumentException { Multimap<K, V> map = HashMultimap.create(); InputStream is = url.openStream(); String content = IOUtils.toString(is, "UTF-8"); BufferedReader br = new BufferedReader(new StringReader(content)); Constructor<K> keyConstructor; Constructor<V> valueConstructor; try { keyConstructor = keyClass.getConstructor(String.class); valueConstructor = valueClass.getConstructor(String.class); } catch (Exception e) { throw new IllegalArgumentException(e); } String line; String[] lineParts; while ((line = br.readLine()) != null) { lineParts = line.split(delimiterRegex); K key; V value; try { key = keyConstructor.newInstance(lineParts[keyColumn - 1]); value = valueConstructor.newInstance(lineParts[valueColumn - 1]); } catch (Exception e) { throw new IllegalArgumentException(e); } map.put(key, value); } return map; }
From source file:net.jofm.metadata.PrimitiveFieldMetaData.java
private static Format createFormatter(Field fieldAnnotation, Class<?> fieldType, String fieldName, FormatConfig formatConfig) {/*from ww w. j ava 2s .c o m*/ String defaultFormat = ""; Class<? extends Format> formatterClazz = null; if (Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) { defaultFormat = formatConfig.getDateFormat(); formatterClazz = DateFormat.class; } else if (String.class.isAssignableFrom(fieldType)) { formatterClazz = StringFormat.class; } else if (fieldType.equals(BigDecimal.class)) { defaultFormat = formatConfig.getBigDecimalFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Short.class) || fieldType.equals(short.class)) { defaultFormat = formatConfig.getShortFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Integer.class) || fieldType.equals(int.class)) { defaultFormat = formatConfig.getIntFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Long.class) || fieldType.equals(long.class)) { defaultFormat = formatConfig.getLongFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Float.class) || fieldType.equals(float.class)) { defaultFormat = formatConfig.getFloatFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Double.class) || fieldType.equals(double.class)) { defaultFormat = formatConfig.getDoubleFormat(); formatterClazz = NumberFormat.class; } else if (fieldType.equals(Boolean.class) || fieldType.equals(boolean.class)) { defaultFormat = formatConfig.getBooleanFormat(); formatterClazz = BooleanFormat.class; } else if (fieldType.isEnum()) { formatterClazz = EnumFormat.class; } if (fieldAnnotation.formatter() != null && !fieldAnnotation.formatter().equals(DefaultFormat.class)) { formatterClazz = fieldAnnotation.formatter(); } if (formatterClazz == null) { throw new FixedMappingException( "Unable to find formatter for field '" + fieldName + "' of type " + fieldType); } try { Constructor<?> c = formatterClazz .getConstructor(new Class[] { Pad.class, char.class, int.class, String.class }); Pad pad = fieldAnnotation.pad() == Pad.DEFAULT ? formatConfig.getPad() : fieldAnnotation.pad(); char padWith = fieldAnnotation.padWith() == Character.MIN_VALUE ? formatConfig.getPadWith() : fieldAnnotation.padWith(); int length = fieldAnnotation.length(); String format = StringUtils.isEmpty(fieldAnnotation.format()) ? defaultFormat : fieldAnnotation.format(); return (Format) c.newInstance(new Object[] { pad, padWith, length, format }); } catch (Exception e) { throw new FixedMappingException( "Unable to instantiate the formatter " + formatterClazz + " for field '" + fieldName + "'", e); } }
From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloader.java
public static Object create(BundleContext bundleContext, String className, List<Object> arguments) throws KettlePluginException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException { ShimBridgingClassloader shimBridgingClassloader = new ShimBridgingClassloader(pluginClassloaderGetter .getPluginClassloader(LifecyclePluginType.class.getCanonicalName(), HADOOP_SPOON_PLUGIN), bundleContext);//from w w w. j a v a 2s .co m Class<?> clazz = Class.forName(className, true, shimBridgingClassloader); if (arguments == null || arguments.size() == 0) { return clazz.newInstance(); } for (Constructor<?> constructor : clazz.getConstructors()) { Class<?>[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == arguments.size()) { boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { Object o = arguments.get(i); if (o != null && !parameterTypes[i].isInstance(o)) { match = false; break; } } if (match) { return constructor.newInstance(arguments.toArray()); } } } throw new InstantiationException( "Unable to find constructor for class " + className + " with arguments " + arguments); }