List of usage examples for java.lang Class getDeclaredConstructor
@CallerSensitive public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
From source file:org.uimafit.spring.SpringContextResourceManager.java
/** * Instantiate a non-visible class.// w w w. j av a 2 s . co m */ @SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T newInstance(String aClassName, Object... aArgs) throws ResourceInitializationException { Constructor constr = null; try { Class<?> cl = Class.forName(aClassName); List<Class> types = new ArrayList<Class>(); List<Object> values = new ArrayList<Object>(); for (int i = 0; i < aArgs.length; i += 2) { types.add((Class) aArgs[i]); values.add(aArgs[i + 1]); } constr = cl.getDeclaredConstructor(types.toArray(new Class[types.size()])); constr.setAccessible(true); return (T) constr.newInstance(values.toArray(new Object[values.size()])); } catch (Exception e) { throw new ResourceInitializationException(e); } finally { if (constr != null) { constr.setAccessible(false); } } }
From source file:com.rockagen.commons.util.ClassUtil.java
/** * obtain constructor list of specified class If recursively is true, obtain * constructor from all class hierarchy/*from w w w . j av a 2 s . c o m*/ * * * @param clazz class * where fields are searching * @param recursively * param * @param parameterTypes parameter types * @return constructor */ public static Constructor<?> getDeclaredConstructor(Class<?> clazz, boolean recursively, Class<?>... parameterTypes) { try { return clazz.getDeclaredConstructor(parameterTypes); } catch (NoSuchMethodException e) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null && recursively) { return getDeclaredConstructor(superClass, true, parameterTypes); } } catch (SecurityException e) { log.error("{}", e.getMessage(), e); } return null; }
From source file:au.com.dw.testdatacapturej.reflection.util.ReflectionUtil.java
/** * Check if a class has a default no parameter constructor. * * @param clazz/* w w w . j av a2 s . com*/ * @return */ public static boolean hasParameterizedConstructor(Class<?> clazz, Class<?>[] parameterTypes) { boolean hasParameterizedConstructor = false; try { Constructor<?> constructor = clazz.getDeclaredConstructor(parameterTypes); if (constructor != null) { hasParameterizedConstructor = true; } } catch (NoSuchMethodException nsme) { // no need to do anything, since this is what we are checking for } catch (Exception e) { e.printStackTrace(); } return hasParameterizedConstructor; }
From source file:org.apache.tajo.storage.OldStorageManager.java
/** * Creates a scanner instance./*from w w w . ja v a2 s . c o m*/ * * @param theClass Concrete class of scanner * @param conf System property * @param taskAttemptId Task id * @param meta Table meta data * @param schema Input schema * @param workDir Working directory * @param <T> * @return The scanner instance */ public static <T> T newAppenderInstance(Class<T> theClass, Configuration conf, TaskAttemptId taskAttemptId, TableMeta meta, Schema schema, Path workDir) { T result; try { Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass); if (meth == null) { meth = theClass.getDeclaredConstructor(DEFAULT_APPENDER_PARAMS); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(theClass, meth); } result = meth.newInstance(new Object[] { conf, taskAttemptId, schema, meta, workDir }); } catch (Exception e) { throw new RuntimeException(e); } return result; }
From source file:io.cloudex.framework.cloud.api.ApiUtils.java
/** * Return an IOException from the metaData error * @param metaData/*ww w.ja v a 2 s . com*/ * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static IOException exceptionFromCloudExError(VmMetaData metaData, String instanceId) { Class clazz = IOException.class; String message = metaData.getMessage(); if (StringUtils.isNoneBlank(metaData.getException())) { try { clazz = Class.forName(metaData.getException()); } catch (ClassNotFoundException e) { log.warn("failed to load exception class from evm"); } } Exception cause; try { Constructor ctor = clazz.getDeclaredConstructor(String.class); ctor.setAccessible(true); cause = (Exception) ctor.newInstance(message); } catch (Exception e) { log.warn("failed to load exception class from evm"); cause = new IOException(message); } return new ProcessorException(PROCESSOR_EXCEPTION + instanceId, cause, instanceId); }
From source file:cn.vlabs.duckling.vwb.service.auth.policy.PolicyUtil.java
private static Principal parsePrincipal(AuthorizationTokenStream ats) throws AuthorizationSyntaxParseException, IOException { String principal = ats.nextUsefulToken(); String className = ats.nextUsefulToken(); String roleName = ats.nextUsefulToken(); if (principal == null || !principal.toLowerCase().equals("principal")) { throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", principal syntax error"); }/*from w w w. j a va2s . co m*/ if (className == null) { throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", className is null"); } if (roleName == null) { throw new AuthorizationSyntaxParseException("Line " + ats.getLineNum() + ", roleName is null"); } else { roleName = StringUtils.strip(roleName, "\""); roleName = roleName.replace("*", "All"); } try { Class<?> clazz = Class.forName(className); return ((Principal) clazz.getDeclaredConstructor(String.class).newInstance(roleName)); } catch (ClassNotFoundException e) { throw new AuthorizationSyntaxParseException( "Line " + ats.getLineNum() + ", ClassNotFoundException, " + e.getMessage()); } catch (Exception e) { throw new AuthorizationSyntaxParseException( "Line " + ats.getLineNum() + ", Exception happens, " + e.getMessage()); } }
From source file:ml.shifu.shifu.util.ClassUtils.java
public static <T> T newInstance(Class<T> clazz) { T result;//from ww w.ja v a2s . c o m try { @SuppressWarnings("unchecked") Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(clazz); if (meth == null) { meth = clazz.getDeclaredConstructor(EMPTY_CLASS_ARRAY); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(clazz, meth); } result = meth.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } return result; }
From source file:com.buaa.cfs.utils.ReflectionUtils.java
/** * Create an object for the given class and initialize it from conf * * @param theClass class of which an object is created * @param conf Configuration//from ww w. j a v a 2 s .c om * * @return a new object */ @SuppressWarnings("unchecked") public static <T> T newInstance(Class<T> theClass, Configuration conf) { T result; try { Constructor<T> meth = (Constructor<T>) CONSTRUCTOR_CACHE.get(theClass); if (meth == null) { meth = theClass.getDeclaredConstructor(EMPTY_ARRAY); meth.setAccessible(true); CONSTRUCTOR_CACHE.put(theClass, meth); } result = meth.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } setConf(result, conf); return result; }
From source file:org.seedstack.seed.core.api.SeedException.java
/** * Create a new subclass of SeedException from an {@link ErrorCode}. * * @param exceptionType the subclass of SeedException to create. * @param errorCode the error code to set. * @param <E> the subtype. * @return the created SeedException./* w w w . j ava2s.c om*/ */ public static <E extends SeedException> E createNew(Class<E> exceptionType, ErrorCode errorCode) { try { Constructor<E> constructor = exceptionType.getDeclaredConstructor(ErrorCode.class); constructor.setAccessible(true); return constructor.newInstance(errorCode); } catch (Exception e) { throw new IllegalArgumentException( exceptionType.getCanonicalName() + " must implement a constructor with ErrorCode as parameter", e); } }
From source file:com.heliosapm.streams.collector.ds.pool.PoolConfig.java
/** * Creates and deploys an ObjectPool based on the passed config props * @param p The configuration properties * @return the created GenericObjectPool *//* w w w .ja va 2 s . c o m*/ @SuppressWarnings({ "rawtypes", "unchecked" }) private static GenericObjectPool<?> deployPool(final Properties p) { final String factoryName = (String) p.remove(POOLED_OBJECT_FACTORY_KEY); final String poolName = p.getProperty(NAME.name().toLowerCase()); if (poolName == null || poolName.trim().isEmpty()) throw new RuntimeException("Pool was not assigned a name"); if (factoryName == null || factoryName.trim().isEmpty()) throw new RuntimeException("No pooled object factory defined"); final GenericObjectPoolConfig cfg = DEFAULT_CONFIG.clone(); try { final Class<PooledObjectFactoryBuilder<?>> clazz = loadFactoryClass(factoryName); final Constructor<PooledObjectFactoryBuilder<?>> ctor = clazz.getDeclaredConstructor(Properties.class); final PooledObjectFactoryBuilder<?> factory = ctor.newInstance(p); for (final String key : p.stringPropertyNames()) { if (isPoolConfig(key)) { final PoolConfig pc = decode(key); pc.apply(cfg, p.get(key)); } } final PooledObjectFactory<?> pooledObjectFactory = factory.factory(); GenericObjectPool<?> pool = new GenericObjectPool(pooledObjectFactory, cfg); pool.setSwallowedExceptionListener(EX_LISTENER); if (factory instanceof PoolAwareFactory) { ((PoolAwareFactory) factory).setPool(pool); } GlobalCacheService.getInstance().put("pool/" + poolName, pool); pool.setAbandonedConfig(Abandoned.create(p)); pool.preparePool(); return pool; } catch (Exception ex) { throw new RuntimeException("Failed to create GenericObjectPool from properties [" + p + "]", ex); } }