List of usage examples for java.lang Class newInstance
@CallerSensitive @Deprecated(since = "9") public T newInstance() throws InstantiationException, IllegalAccessException
From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImpl.java
private static Driver getJdbcDriver(String jdbcDriverClassPath, URLClassLoader urlClassLoader, String className) {/*from w w w. ja v a2s. com*/ Class<?> aClass = null; try { aClass = Class.forName(className, true, urlClassLoader); } catch (ClassNotFoundException e) { throw new IllegalStateException("Unable to locate class " + className + " in " + jdbcDriverClassPath); } Driver driver = null; try { driver = (Driver) aClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException("Unable to instantiate driver from class " + className, e); } catch (IllegalAccessException e) { throw new IllegalStateException("Unable to access driver class " + className + "; " + e, e); } return driver; }
From source file:com.dsj.core.beans.CollectionFactory.java
/** * Create the most approximate collection for the given collection class. * <p>Tries to create the given collection class. If that fails, * an ArrayList, TreeSet or linked Set will be used as fallback for * a List, SortedSet or Set, respectively. * @param collectionClass the original collection class * @param initialCapacity the initial capacity * @return the new collection instance/*w ww. ja v a2s . co m*/ * @see java.util.ArrayList * @see java.util.TreeSet * @see #createLinkedSetIfPossible */ public static Collection createApproximateCollection(Class collectionClass, int initialCapacity) { Assert.notNull(collectionClass, "Collection class must not be null"); if (!collectionClass.isInterface()) { try { return (Collection) collectionClass.newInstance(); } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug("Could not instantiate collection type [" + collectionClass.getName() + "]: " + ex.getMessage()); } } } if (List.class.isAssignableFrom(collectionClass)) { return new ArrayList(initialCapacity); } else if (SortedSet.class.isAssignableFrom(collectionClass)) { return new TreeSet(); } else { return createLinkedSetIfPossible(initialCapacity); } }
From source file:Main.java
/** * Converts the given array to a set with the given type. Works like * {@link Arrays#asList(Object...)}.//from w w w . ja v a2 s .com * * @param <T> * The type of the set values. * @param setType * The set type to return. * @param arr * The array to convert into a set. * @return An object of the given set or, if, and only if, an error * occurred, <code>null</code>. */ @SuppressWarnings("unchecked") public static <T> Set<T> toSet(@SuppressWarnings("rawtypes") final Class<? extends Set> setType, final T... arr) { assert setType != null : "SetType cannot be null!"; assert !Modifier.isAbstract(setType.getModifiers()) : "SetType cannot be abstract!"; assert !setType.isInterface() : "SetType cannot be an interface!"; assert arr != null : "Arr cannot be null!"; Set<T> result = null; try { result = setType.newInstance(); for (final T t : arr) { result.add(t); } } catch (final InstantiationException ex) { ex.printStackTrace(); } catch (final IllegalAccessException ex) { ex.printStackTrace(); } return result; }
From source file:com.impetus.ankush.common.utils.JsonMapperUtil.java
/** * Object from map./*from w ww.jav a 2s.co m*/ * * @param <S> * the generic type * @param values * the values * @param targetClass * the target class * @return the s * @throws IllegalArgumentException * the illegal argument exception * @throws IllegalAccessException * the illegal access exception * @throws InstantiationException * the instantiation exception * @throws InvocationTargetException * the invocation target exception * @throws Exception * the exception */ public static <S> S objectFromMap(Map<String, Object> values, Class<S> targetClass) throws IllegalArgumentException, IllegalAccessException, InstantiationException, InvocationTargetException, Exception { // Creating target class object. S mainObject = targetClass.newInstance(); // Getting fields of the class. Field[] fields = targetClass.getDeclaredFields(); Map<String, Field> fieldMap = new HashMap<String, Field>(); for (Field field : fields) { // Putting fields in fieldMap fieldMap.put(field.getName(), field); } // Iterating over the key set in value map. for (String mainKey : values.keySet()) { if (values.get(mainKey) instanceof LinkedHashMap) { // Creating target object type. if (fieldMap.get(mainKey) == null) { continue; } Object subObject = fieldMap.get(mainKey).getType().newInstance(); // Casting to map. Map subValues = (Map) values.get(mainKey); // Iterating over the map keys. for (Object subKey : subValues.keySet()) { BeanUtils.setProperty(subObject, (String) subKey, subValues.get(subKey)); } // setting the sub object in bean main object. BeanUtils.setProperty(mainObject, mainKey, subObject); } else { // setting the value in bean main object. BeanUtils.setProperty(mainObject, mainKey, values.get(mainKey)); } } return mainObject; }
From source file:eagle.storage.jdbc.entity.JdbcEntitySerDeserHelper.java
/** * * @param row//ww w . j a va2s . com * @param entityDefinition * @param <E> * @return * @throws IllegalAccessException * @throws InstantiationException * @throws InvocationTargetException * @throws NoSuchMethodException */ public static <E extends TaggedLogAPIEntity> E buildEntity(Map<String, Object> row, JdbcEntityDefinition entityDefinition) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { EntityDefinition ed = entityDefinition.getInternal(); Class<? extends TaggedLogAPIEntity> clazz = ed.getEntityClass(); if (clazz == null) { throw new NullPointerException("Entity class of service " + ed.getService() + " is null"); } TaggedLogAPIEntity obj = clazz.newInstance(); Map<String, Qualifier> map = ed.getDisplayNameMap(); for (Map.Entry<String, Object> entry : row.entrySet()) { // timestamp; if (JdbcConstants.TIMESTAMP_COLUMN_NAME.equals(entry.getKey())) { obj.setTimestamp((Long) entry.getValue()); continue; } // set metric as prefix for generic metric if (entityDefinition.getInternal().getService().equals(GenericMetricEntity.GENERIC_METRIC_SERVICE) && JdbcConstants.METRIC_NAME_COLUMN_NAME.equals(entry.getKey())) { obj.setPrefix((String) entry.getValue()); continue; } // rowkey: uuid if (JdbcConstants.ROW_KEY_COLUMN_NAME.equals(entry.getKey())) { obj.setEncodedRowkey((String) entry.getValue()); continue; } Qualifier q = map.get(entry.getKey().toLowerCase()); if (q == null) { // if it's not pre-defined qualifier, it must be tag unless it's a bug if (obj.getTags() == null) { obj.setTags(new HashMap<String, String>()); } obj.getTags().put(entry.getKey(), (String) entry.getValue()); continue; } // parse different types of qualifiers String fieldName = q.getDisplayName(); // PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(obj, fieldName); PropertyDescriptor pd = getPropertyDescriptor(obj, fieldName); if (entry.getValue() != null) { pd.getWriteMethod().invoke(obj, entry.getValue()); } } if (!entityDefinition.getInternal().getService().equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { obj.setPrefix(entityDefinition.getInternal().getPrefix()); } return (E) obj; }
From source file:it.greenvulcano.gvesb.http.ProtocolFactory.java
/** * @param protocolConfig//w ww. j a va2 s .c o m * @return * @throws Exception */ public static Protocol create(Node protocolConfig) throws Exception { String scheme = XMLConfig.get(protocolConfig, "@protocol-scheme"); String socketFactoryClassName = XMLConfig.get(protocolConfig, "@protocol-socket-factory"); int defaultPort = XMLConfig.getInteger(protocolConfig, "@protocol-default-port"); Class<?> socketFactoryClass = Class.forName(socketFactoryClassName); Object socketFactoryInstance = null; Node constructorNode = XMLConfig.getNode(protocolConfig, "constructor-args"); if (constructorNode != null) { socketFactoryInstance = createObjectUsingConstructor(socketFactoryClass, constructorNode); } else { socketFactoryInstance = socketFactoryClass.newInstance(); } return new Protocol(scheme, (ProtocolSocketFactory) socketFactoryInstance, defaultPort); }
From source file:net.itransformers.topologyviewer.gui.VertexFilterFactory.java
static VertexPredicateFilter<String, String> createVertexFilter(final FilterType filter, final Map<String, DataMatcher> matcherMap, final Map<String, GraphMLMetadata<String>> vertexMetadata, final Graph<String, String> graph1) { return new VertexPredicateFilter<String, String>(new Predicate<String>() { public boolean evaluate(String v) { if (graph1.getIncidentEdges(v).isEmpty()) { return false; } else { if (filter == null) return true; List<IncludeType> includes = filter.getInclude(); String filterType = filter.getType(); if (filterType == null) { filterType = "or"; }/* w ww. j av a 2s .c o m*/ boolean hasNodeInlcude = false; for (IncludeType include : includes) { if (ForType.NODE.equals(include.getFor())) { String matcher = include.getMatcher(); if (matcher == null) { matcher = "default"; } if (include.getClassType() == null) { final String dataKey = include.getDataKey(); //include all nodes if (dataKey == null) { hasNodeInlcude = true; continue; } //the evaluated node dosn't have that dataKey if (vertexMetadata.get(dataKey) == null) { logger.debug("No data is defined in vertex metadata for dataKey=" + dataKey); continue; } //the evaluated node has that dataKey String value = vertexMetadata.get(dataKey).transformer.transform(v); //Evaluate only if the value is not null if (value != null) { //Evaluate multiplicity e.g multiple values for single data key split by commas String[] dataValues = value.split(","); //get the value from the include filter String includeDataValue = include.getDataValue(); //Circle around the actual values and perform the datamatch DataMatcher matcherInstance = matcherMap.get(matcher); //If we have an "and" filter if ("and".equals(filterType)) { for (String dataValue : dataValues) { // boolean matchResult = ; hasNodeInlcude = false; if (matcherInstance.compareData(dataValue, includeDataValue)) { logger.debug("Node selected: " + v + " by filter " + filter.getName() + " with include " + include.getDataKey() + " with value " + dataValue); hasNodeInlcude = true; } } if (!hasNodeInlcude) { return false; } //If we have an "or" filter } else { for (String dataValue : dataValues) { if (matcherInstance.compareData(dataValue, includeDataValue)) { logger.debug("Node " + v + " has been selected from filter " + filter.getName() + " by property " + include.getDataKey() + " with value " + dataValue); hasNodeInlcude = true; } else { logger.debug("Node" + v + " has not been selected from filter " + filter.getName() + " by property " + include.getDataKey() + " with value " + dataValue); } } } } } else { //We have totally custom filter from class String type = include.getClassType(); Class<?> includeClazz; try { includeClazz = Class.forName(type); VertexIncluder includeInst = (VertexIncluder) includeClazz.newInstance(); boolean hasToInlcude = includeInst.hasToInclude(v, vertexMetadata, graph1); if ("and".equals(filterType)) { if (!hasToInlcude) { return false; } } else { if (hasToInlcude) { hasNodeInlcude = true; } } } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (InstantiationException e) { e.printStackTrace(); return false; } catch (IllegalAccessException e) { e.printStackTrace(); return false; } } } } //Finally if the has to include flag is set include if (!hasNodeInlcude) { logger.info("Node " + v + " has not been selected"); return false; } else { logger.info("Node " + v + " has been selected"); return true; } } } }); }
From source file:com.google.android.apps.authenticator.testability.DependencyInjector.java
public static synchronized OptionalFeatures getOptionalFeatures() { if (sOptionalFeatures == null) { try {// w w w.j av a2 s . c o m Class<?> resultClass = Class.forName( AuthenticatorActivity.class.getPackage().getName() + ".NonMarketBuildOptionalFeatures"); try { sOptionalFeatures = (OptionalFeatures) resultClass.newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to instantiate optional features module", e); } } catch (ClassNotFoundException e) { sOptionalFeatures = new MarketBuildOptionalFeatures(); } } return sOptionalFeatures; }
From source file:com.aurel.track.itemNavigator.viewPlugin.ViewPluginBL.java
public synchronized static IssueListViewPlugin getPlugin(String className) { if (cachePlugins == null) { cachePlugins = new HashMap<String, Class>(); }// w w w . j ava2 s .c o m Class pluginClass = (Class) cachePlugins.get(className); if (pluginClass == null) { try { pluginClass = Class.forName(className); } catch (ClassNotFoundException e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); return null; } cachePlugins.put(className, pluginClass); } try { return (IssueListViewPlugin) pluginClass.newInstance(); } catch (InstantiationException e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } catch (IllegalAccessException e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); } return null;//plugin class problem }
From source file:com.opensymphony.xwork.util.DomHelper.java
/** * Creates a W3C Document that remembers the location of each element in * the source file. The location of element nodes can then be retrieved * using the {@link #getLocationObject(Element)} method. * * @param inputSource the inputSource to read the document from * @param dtdMappings a map of DTD names and public ids *///w w w . j av a 2 s . co m public static Document parse(InputSource inputSource, Map dtdMappings) { SAXParserFactory factory = null; String parserProp = System.getProperty("xwork.saxParserFactory"); if (parserProp != null) { try { Class clazz = ObjectFactory.getObjectFactory().getClassInstance(parserProp); factory = (SAXParserFactory) clazz.newInstance(); } catch (ClassNotFoundException e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } catch (Exception e) { LOG.error("Unable to load saxParserFactory set by system property 'xwork.saxParserFactory': " + parserProp, e); } } if (factory == null) { factory = SAXParserFactory.newInstance(); } factory.setValidating((dtdMappings != null)); factory.setNamespaceAware(true); SAXParser parser = null; try { parser = factory.newSAXParser(); } catch (Exception ex) { throw new XworkException("Unable to create SAX parser", ex); } DOMBuilder builder = new DOMBuilder(); // Enhance the sax stream with location information ContentHandler locationHandler = new LocationAttributes.Pipe(builder); try { parser.parse(inputSource, new StartHandler(locationHandler, dtdMappings)); } catch (Exception ex) { throw new XworkException(ex); } return builder.getDocument(); }