protected void scanClasspathForMappings(String basePackage) { FastClasspathScanner scanner = new FastClasspathScanner(basePackage); scanner.matchClassesWithAnnotation(ContentItemMapping.class, classWithAnnotation -> { ContentItemMapping contentItemMapping = classWithAnnotation.getAnnotation(ContentItemMapping.class); registerType(contentItemMapping.value(), classWithAnnotation); }).matchSubclassesOf(InlineContentItemsResolver.class, subclass -> { try { registerInlineContentItemsResolver(ConstructorUtils.invokeConstructor(subclass, null)); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { // No default constructor, no InlineContentItemsResolver. } }).scan(); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public MutableRepositoryItemExt read(ObjectDataInput in) throws IOException { try { String gsonString = in.readUTF(); System.out.println("MutableRepositoryItemExtHazelcastSerializer deserialize " + System.currentTimeMillis() + " " + gsonString); Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); Map<String, Object> cache = gson.fromJson(gsonString, Map.class); String javaClassName = (String) cache.get("__class"); String repositoryId = (String) cache.get("__repositoryId"); Class beanClass = Class.forName(javaClassName); MutableRepositoryItemExt mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(beanClass, null); mutableRepositoryItemExt.setRepositoryId(repositoryId); mutableRepositoryItemExt.setCachedData(cache); return mutableRepositoryItemExt; } catch (Exception e) { throw new RuntimeException(e); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Override public MutableRepositoryItemExt deserialize(DataInput in, int available) throws IOException { try { System.out.println("MutableRepositoryItemExtMapDBSerializer deserialize"); String gsonString = in.readUTF(); Gson gson = new GsonBuilder().create(); Map<String, Object> cache = gson.fromJson(gsonString, Map.class); String javaClassName = (String) cache.get("__class"); String repositoryId = (String) cache.get("__repositoryId"); Class beanClass = Class.forName(javaClassName); MutableRepositoryItemExt mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(beanClass, null); mutableRepositoryItemExt.setRepositoryId(repositoryId); mutableRepositoryItemExt.setCachedData(cache); return mutableRepositoryItemExt; } catch (Exception e) { throw new RuntimeException(e); } }
public static Constructor<?> findPublicConstructor(Class<?> klass) { Validate.notNull(klass, "Null class not allowed."); Constructor<?> nullConstructor = ConstructorUtils.getAccessibleConstructor(klass, new Class<?>[0]); if (nullConstructor != null) { return nullConstructor; } Constructor<?>[] constructorArray = klass.getConstructors(); for (Constructor<?> constructor: constructorArray) { if (Modifier.isPublic(constructor.getModifiers())) { return constructor; } } return null; }
/** * Returns concrete class, for the given collection interface or abstract class. If given class * is already concrete, it will return that class. * * @param collectionClass collection class to find implementation for * @return concrete class */ public static Class<? extends Collection> suggestCollectionImplementation(Class<? extends Collection> collectionClass) { Class<? extends Collection> collClass = null; if (collectionClass != null && (collectionClass.isInterface() || Modifier.isAbstract(collectionClass.getModifiers()))) { // for interface such as List (or abstract classes), go to the implementation map collClass = COLLECTION_IMPLEMENTATIONS.get(collectionClass.getName()); } else if (collectionClass != null && ConstructorUtils.getAccessibleConstructor(collectionClass, new Class[0]) == null) { // this is an implementation class, but no default constructor, datanucleus collection for example // go through interfaces and try to find an interface we have in the collection map for (Object intClassObj : ClassUtils.getAllInterfaces(collectionClass)) { Class intClass = (Class) intClassObj; collClass = COLLECTION_IMPLEMENTATIONS.get(intClass.getName()); if (collClass != null) { break; } } } else { // this is an implementation that can be instantiated, return it collClass = collectionClass; } return collClass == null ? ArrayList.class : collClass; // NOPMD - bug in PMD, objects to ArrayList.class here }
<T> T convert(ContentItem item, Map<String, ContentItem> modularContent, Class<T> tClass) { if (tClass == Object.class) { Class<?> mappingClass = contentTypeToClassMapping.get(item.getSystem().getType()); if (mappingClass == null) { return (T) item; } return (T) convert(item, modularContent, mappingClass); } if (tClass == ContentItem.class) { return (T) item; } T bean = null; try { //Invoke the default constructor bean = ConstructorUtils.invokeConstructor(tClass, null); //Get the bean properties Field[] fields = tClass.getDeclaredFields(); //Inject mappings for (Field field : fields) { Object value = getValueForField(item, modularContent, bean, field); if (value != null) { BeanUtils.setProperty(bean, field.getName(), value); } } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) { handleReflectionException(e); } //Return bean return bean; }
/** * New instance. * * @param <T> * the generic type * @param clas * the clas * @param params * the params * @return the t */ public static <T> T newInstance(final Class<T> clas, final Object... params) { try { final Class<?>[] paramClasses = JKObjectUtil.toClassesFromObjects(params); if (paramClasses.length == 0) { return clas.newInstance(); } return ConstructorUtils.invokeConstructor(clas, params); } catch (final Exception e) { throw new RuntimeException(e); } }
@SuppressWarnings({ "rawtypes", "unchecked" }) protected MutableRepositoryItemExt create(MutableRepositoryItem in, Class beanClass) throws RepositoryException { MutableRepositoryItemExt mutableRepositoryItemExt = null; try { mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(beanClass, null); mutableRepositoryItemExt.setDelegate(in); mutableRepositoryItemExt.setRepositoryId(in.getRepositoryId()); String className = beanClass.getCanonicalName(); String key = in.getRepositoryId() + SPLIT_CHAR + className; itemCache.put(key, mutableRepositoryItemExt); } catch (Exception e) { throw new RepositoryException(e); } return mutableRepositoryItemExt; }
@SuppressWarnings({ "unchecked", "rawtypes" }) protected List wrapList(List<RepositoryItem> in, String repositryId, String propertyName, Class clazz) { List<RepositoryItem> list = new ArrayList<RepositoryItem>(); String itemDescriptorName = ""; try { itemDescriptorName = this.getItemDescriptor().getItemDescriptorName(); for (RepositoryItem repositoryItem : in) { MutableRepositoryItemExt mutableRepositoryItemExt = getRepository().getItemCache().get(repositoryItem.getRepositoryId() + GenericsRepository.SPLIT_CHAR + clazz.getCanonicalName()); if (mutableRepositoryItemExt != null) { // is the item already in the cache. // this can happen if product -- childSkus -- parantProducts so running this check ensures that objects are // created only once list.add(mutableRepositoryItemExt); } else { mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(clazz, null); mutableRepositoryItemExt.setDelegate(repositoryItem); mutableRepositoryItemExt.setRepositoryId(repositoryItem.getRepositoryId()); list.add(mutableRepositoryItemExt); getRepository().getItemCache().put(mutableRepositoryItemExt.getRepositoryId() + GenericsRepository.SPLIT_CHAR + mutableRepositoryItemExt.getClass().getCanonicalName(), mutableRepositoryItemExt); } } } catch (Exception e) { throw new RuntimeException(e); } List result = null; if (getRepository().isChangeAware()) { result = new ChangeAwareList(list, this, itemDescriptorName, (ApplicationLogging) this.getRepository()); } else { result = list; } return result; }
@SuppressWarnings({ "unchecked", "rawtypes" }) protected Set wrapSet(Set<RepositoryItem> in, String repositryId, String propertyName, Class clazz) { Set<RepositoryItem> set = new HashSet<RepositoryItem>(); String itemDescriptorName = ""; try { itemDescriptorName = this.getItemDescriptor().getItemDescriptorName(); for (RepositoryItem repositoryItem : in) { MutableRepositoryItemExt mutableRepositoryItemExt = getRepository().getItemCache().get(repositoryItem.getRepositoryId() + GenericsRepository.SPLIT_CHAR + clazz.getCanonicalName()); if (mutableRepositoryItemExt != null) { // is the item already in the cache. // this can happen if product -- childSkus -- parantProducts so running this check ensures that objects are // created only once set.add(mutableRepositoryItemExt); } else { mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(clazz, null); mutableRepositoryItemExt.setDelegate(repositoryItem); mutableRepositoryItemExt.setRepositoryId(repositoryItem.getRepositoryId()); set.add(mutableRepositoryItemExt); getRepository().getItemCache().put(mutableRepositoryItemExt.getRepositoryId() + GenericsRepository.SPLIT_CHAR + mutableRepositoryItemExt.getClass().getCanonicalName(), mutableRepositoryItemExt); } } } catch (Exception e) { throw new RuntimeException(e); } Set result = null; if (getRepository().isChangeAware()) { result = new ChangeAwareSet(set, this, itemDescriptorName); } else { result = set; } return result; }
@SuppressWarnings({ "unchecked", "rawtypes" }) protected Map wrapMap(Map<String, RepositoryItem> in, String repositryId, String propertyName, Class clazz) { Map<String, RepositoryItem> map = new HashMap<String, RepositoryItem>(); String itemDescriptorName = ""; Set<String> keySet = in.keySet(); try { itemDescriptorName = this.getItemDescriptor().getItemDescriptorName(); for (String key : keySet) { RepositoryItem repositoryItem = map.get(key); MutableRepositoryItemExt mutableRepositoryItemExt = getRepository().getItemCache().get(repositoryItem.getRepositoryId() + clazz.getCanonicalName()); if (mutableRepositoryItemExt != null) { map.put(key, mutableRepositoryItemExt); } else { mutableRepositoryItemExt = ConstructorUtils.invokeExactConstructor(clazz, null); mutableRepositoryItemExt.setDelegate(repositoryItem); mutableRepositoryItemExt.setRepositoryId(repositoryItem.getRepositoryId()); map.put(key, mutableRepositoryItemExt); getRepository().getItemCache().put(mutableRepositoryItemExt.getRepositoryId() + GenericsRepository.SPLIT_CHAR + mutableRepositoryItemExt.getClass().getCanonicalName(), mutableRepositoryItemExt); } } } catch (Exception e) { throw new RuntimeException(e); } Map result = null; if (getRepository().isChangeAware()) { result = new ChangeAwareMap(map, this, itemDescriptorName); } else { result = map; } return result; }
/** * <p>If the wrapperClassName property is not null, return a Context of * the type specified by wrapperClassName, instantiated using a single-arg * constructor which takes the context passed as an argument to this * method.</p> * * <p>This method throws an exception if the wrapperClass cannot be found, * or if there are any errors instantiating the wrapping context.</p> * * @param context Context we are processing * @return Context wrapper * @throws ClassNotFoundException On failed instantiation * @throws InstantiationException On failed instantiation * @throws InvocationTargetException On failed instantiation * @throws IllegalAccessException On failed instantiation * @throws NoSuchMethodException On failed instantiation */ protected Context getContext(Context context) throws ClassNotFoundException, InstantiationException, InvocationTargetException, IllegalAccessException, NoSuchMethodException { if (wrapperClassName == null) { if (LOG.isDebugEnabled()) { LOG.debug("No defined wrapper class; " + "returning original context."); } return context; } if (LOG.isDebugEnabled()) { LOG.debug("Looking for wrapper class: " + wrapperClassName); } Class wrapperClass = ClassUtils.getApplicationClass(wrapperClassName); if (LOG.isDebugEnabled()) { LOG.debug("Instantiating wrapper class"); } return (Context) ConstructorUtils.invokeConstructor(wrapperClass, new Object[] { context }); }
/** * <p> Set and cache ActionContext class. </p><p> If there is a custom * class provided and if it uses our "preferred" constructor, cache a * reference to that constructor rather than looking it up every time. * </p> * * @param actionContextClass The ActionContext class to process */ private void setActionContextClass(Class actionContextClass) { this.actionContextClass = actionContextClass; if (actionContextClass != null) { this.servletActionContextConstructor = ConstructorUtils.getAccessibleConstructor(actionContextClass, SERVLET_ACTION_CONTEXT_CTOR_SIGNATURE); } else { this.servletActionContextConstructor = null; } }
/** * newInstance() execution properly wrapped with exception handling. * @param klass * @return */ public static Object safeNewInstance(Class<?> klass, Object[] constructorArgs) { Validate.notNull(klass, "Null class not allowed."); try { return ConstructorUtils.invokeConstructor(klass, constructorArgs); } catch (Exception e) { throw new BeanTesterException("Failed to instantiate bean using newInstance()", e) .addContextValue("className", klass.getName()); } }
protected SequenceManager createSequenceManager(PersistenceBroker broker) { String sequenceManagerClassName = ConfigContext.getCurrentContextConfig().getProperty(SEQUENCE_MANAGER_CLASS_NAME_PROPERTY); try { Object sequenceManagerObject = ConstructorUtils.invokeConstructor(Class.forName(sequenceManagerClassName), broker); if (!(sequenceManagerObject instanceof SequenceManager)) { throw new ConfigurationException("The configured sequence manager ('" + sequenceManagerClassName + "') is not an instance of '" + SequenceManager.class.getName() + "'"); } return (SequenceManager) sequenceManagerObject; } catch (Exception e) { String message = "Unable to configure SequenceManager specified by " + SEQUENCE_MANAGER_CLASS_NAME_PROPERTY + " KualiConfigurationService property"; LOG.fatal(message, e); throw new RuntimeException(message, e); } }
protected Object writeValues(Map<String, Object> values, Class clazz) { try { Object value = ConstructorUtils.invokeConstructor(clazz, null); writeValues(values, value); return value; } catch (Exception e) { getLogger().warn("Unable to create instance for class {}: ", clazz.getName()); } return null; }
protected static Object loadObject(Class<?> objectClass, Object[] constructorParams, Class<?>[] constructorParamTypes) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { return ConstructorUtils.invokeConstructor(objectClass, constructorParams, constructorParamTypes); }
private static boolean isInstantiable(Class<?> clazz) { boolean abs = Modifier.isAbstract(clazz.getModifiers()); boolean hasConstuctor = ConstructorUtils.getAccessibleConstructor(clazz, new Class[0]) != null; return !clazz.isInterface() && !abs && hasConstuctor; }