Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

In this page you can find the example usage for java.lang Class getDeclaredConstructor.

Prototype

@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Usage

From source file:Main.java

public static <T> Constructor<T> findConstructor(Class<T> paramClass, boolean paramBoolean)
        throws IllegalArgumentException {
    Constructor localConstructor;
    try {/*  w  w w .  j  av  a 2  s  . co m*/
        localConstructor = paramClass.getDeclaredConstructor(new Class[0]);
        if (paramBoolean) {
            checkAndFixAccess(localConstructor);
            return localConstructor;
        }
        if (!Modifier.isPublic(localConstructor.getModifiers()))
            throw new IllegalArgumentException("Default constructor for " + paramClass.getName()
                    + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type");
    } catch (NoSuchMethodException localNoSuchMethodException) {
        return null;
    } catch (Exception localException) {
        while (true)
            unwrapAndThrowAsIAE(localException, "Failed to find default constructor of class "
                    + paramClass.getName() + ", problem: " + localException.getMessage());
    }
    return localConstructor;
}

From source file:msi.gama.util.file.GamaFileMetaData.java

public static <T extends IGamaFileMetaData> T from(final String s, final long stamp, final Class<T> clazz,
        final boolean includeOutdated) {
    T result = null;/*ww w.  j a  v a2s .co  m*/
    try {
        final Constructor<T> c = clazz.getDeclaredConstructor(String.class);
        result = c.newInstance(s);
        final boolean hasFailed = result.hasFailed();
        if (!hasFailed && !includeOutdated && result.getModificationStamp() != stamp) {
            return null;
        }
    } catch (final Exception ignore) {
        DEBUG.ERR("Error loading metadata " + s + " : " + ignore.getClass().getSimpleName() + ":"
                + ignore.getMessage());
        if (ignore instanceof InvocationTargetException && ignore.getCause() != null) {
            ignore.getCause().printStackTrace();
        }
    }
    return result;
}

From source file:com.adaptris.core.fs.FsHelper.java

public static FileFilter createFilter(String filterExpression, String filterImpl) throws Exception {
    FileFilter result = null;/*from w ww . j a  v  a  2 s.  c om*/
    if (isEmpty(filterExpression)) {
        result = new NoOpFileFilter();
    } else {
        Class[] paramTypes = { filterExpression.getClass() };
        Object[] args = { filterExpression };
        Class c = Class.forName(filterImpl);
        Constructor cnst = c.getDeclaredConstructor(paramTypes);
        result = (FileFilter) cnst.newInstance(args);
    }
    return logWarningIfRequired(result);
}

From source file:org.jdto.impl.BeanClassUtils.java

/**
 * Find a constructor in the class for the argument types. This method
 * converts any checked exception in unchecked exception.
 *
 * @param cls the class whos constructor will be found.
 * @param types the types of the parameters of the constructor.
 * @return the constructor of the given class which has the given parameter
 * types./*from   w w  w  .  j a va 2 s.  c o  m*/
 */
public static Constructor safeGetConstructor(Class cls, Class[] types) {
    try {
        return cls.getDeclaredConstructor(types);
    } catch (Exception ex) {
        logger.error("Error while trying to find constructor for class " + cls.getCanonicalName(), ex);
        throw new RuntimeException("Error while trying to find constructor for class " + cls.getCanonicalName(),
                ex);
    }
}

From source file:org.apache.hadoop.hbase.util.ReflectionUtils.java

@SuppressWarnings("unchecked")
public static <T> T instantiateWithCustomCtor(String className, Class<?>[] ctorArgTypes, Object[] ctorArgs) {
    try {//  ww w .  jav a  2  s.  c om
        Class<? extends T> resultType = (Class<? extends T>) Class.forName(className);
        Constructor<? extends T> ctor = resultType.getDeclaredConstructor(ctorArgTypes);
        return instantiate(className, ctor, ctorArgs);
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Unable to find " + className, e);
    } catch (NoSuchMethodException e) {
        throw new UnsupportedOperationException("Unable to find suitable constructor for class " + className,
                e);
    }
}

From source file:org.apache.bval.util.reflection.Reflection.java

/**
 * Get the declared constructor from {@code clazz}.
 * @param T generic type// ww w  .java2  s  .c om
 * @param clazz
 * @param parameters
 * @return {@link Constructor} or {@code null}
 */
public static <T> Constructor<T> getDeclaredConstructor(final Class<T> clazz, final Class<?>... parameters) {
    try {
        return clazz.getDeclaredConstructor(parameters);
    } catch (final NoSuchMethodException e) {
        return null;
    }
}

From source file:org.apache.nifi.spring.SpringContextFactory.java

/**
 * Creates and instance of Spring Application Context scoped within a
 * dedicated Class Loader./*from   w  w  w .j  a  v  a  2  s. co  m*/
 * <br>
 * The core task of this factory is to load delegate that supports message
 * exchange with Spring Application Context ({@link SpringDataExchanger})
 * using the same class loader used to load the Application Context. Such
 * class loader isolation is required to ensure that multiple instances of
 * Application Context (representing different applications) and the
 * corresponding delegate can exist per single instance of Spring NAR.
 * <br>
 * The mechanism used here is relatively simple. While
 * {@link SpringDataExchanger} is available to the current class loader and
 * would normally be loaded once per instance of NAR, the below factory
 * method first obtains class bytes for {@link SpringDataExchanger} and then
 * loads it from these bytes via ClassLoader.defineClass(..) method, thus
 * ensuring that multiple instances of {@link SpringDataExchanger} class can
 * exist and everything that is loaded within its scope is using its class
 * loader. Upon exit, the class loader is destroyed via close method
 * essentially with everything that it loaded.
 * <br>
 * Also, during the initialization of {@link SpringDataExchanger} the new
 * class loader is set as Thread.contextClassLoader ensuring that if there
 * are any libraries used by Spring beans that rely on loading resources via
 * Thread.contextClassLoader can find such resources.
 */
static SpringDataExchanger createSpringContextDelegate(String classpath, String config) {
    List<URL> urls = gatherAdditionalClassPathUrls(classpath);
    SpringContextClassLoader contextCl = new SpringContextClassLoader(urls.toArray(new URL[] {}),
            SpringContextFactory.class.getClassLoader());
    ClassLoader tContextCl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(contextCl);
    try {
        InputStream delegateStream = contextCl
                .getResourceAsStream(SC_DELEGATE_NAME.replace('.', '/') + ".class");
        byte[] delegateBytes = IOUtils.toByteArray(delegateStream);
        Class<?> clazz = contextCl.doDefineClass(SC_DELEGATE_NAME, delegateBytes, 0, delegateBytes.length);
        Constructor<?> ctr = clazz.getDeclaredConstructor(String.class);
        ctr.setAccessible(true);
        SpringDataExchanger springDelegate = (SpringDataExchanger) ctr.newInstance(config);
        if (logger.isInfoEnabled()) {
            logger.info("Successfully instantiated Spring Application Context from '" + config + "'");
        }
        return springDelegate;
    } catch (Exception e) {
        try {
            contextCl.close();
        } catch (Exception e2) {
            // ignore
        }
        throw new IllegalStateException("Failed to instantiate Spring Application Context. Config path: '"
                + config + "'; Classpath: " + Arrays.asList(urls), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tContextCl);
    }
}

From source file:org.apache.samza.sql.testutil.ReflectionUtils.java

/**
 * Create an instance of the specified class with constuctor
 * matching the argument array./*  www .  ja  va2s . c  o m*/
 * @param clazz name of the class
 * @param args argument array
 * @param <T> type fo the class
 * @return instance of the class, or null if anything went wrong
 */
@SuppressWarnings("unchecked")
public static <T> T createInstance(String clazz, Object... args) {
    Validate.notNull(clazz, "null class name");
    try {
        Class<T> classObj = (Class<T>) Class.forName(clazz);
        Class<?>[] argTypes = new Class<?>[args.length];
        IntStream.range(0, args.length).forEach(i -> argTypes[i] = args[i].getClass());
        Constructor<T> ctor = classObj.getDeclaredConstructor(argTypes);
        return ctor.newInstance(args);
    } catch (Exception e) {
        LOG.warn("Failed to create instance for: " + clazz, e);
        return null;
    }
}

From source file:com.github.dryangkun.hbase.tidx.hive.HBaseTableSnapshotInputFormatUtil.java

/**
 * Create a bare TableSnapshotRegionSplit. Needed because Writables require a
 * default-constructed instance to hydrate from the DataInput.
 *
 * TODO: remove once HBASE-11555 is fixed.
 *///www  . j a  va 2s  .c o m
public static InputSplit createTableSnapshotRegionSplit() {
    try {
        assertSupportsTableSnapshots();
    } catch (RuntimeException e) {
        LOG.debug("Probably don't support table snapshots. Returning null instance.", e);
        return null;
    }

    try {
        Class<? extends InputSplit> resultType = (Class<? extends InputSplit>) Class
                .forName(TABLESNAPSHOTREGIONSPLIT_CLASS);
        Constructor<? extends InputSplit> cxtor = resultType.getDeclaredConstructor(new Class[] {});
        cxtor.setAccessible(true);
        return cxtor.newInstance(new Object[] {});
    } catch (ClassNotFoundException e) {
        throw new UnsupportedOperationException("Unable to find " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (IllegalAccessException e) {
        throw new UnsupportedOperationException(
                "Unable to access specified class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (InstantiationException e) {
        throw new UnsupportedOperationException(
                "Unable to instantiate specified class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (InvocationTargetException e) {
        throw new UnsupportedOperationException(
                "Constructor threw an exception for " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    } catch (NoSuchMethodException e) {
        throw new UnsupportedOperationException(
                "Unable to find suitable constructor for class " + TABLESNAPSHOTREGIONSPLIT_CLASS, e);
    }
}

From source file:org.cloudata.core.common.util.ReflectionUtils.java

/** Create an object for the given class and initialize it from conf
 * //from  ww  w . j a va2 s.co  m
 * @param theClass class of which an object is created
 * @param conf Configuration
 * @return a new object
 */
public static Object newInstance(Class<?> theClass, CloudataConf conf) {
    Object result;
    try {
        Constructor meth = CONSTRUCTOR_CACHE.get(theClass);
        if (meth == null) {
            meth = theClass.getDeclaredConstructor(emptyArray);
            meth.setAccessible(true);
            CONSTRUCTOR_CACHE.put(theClass, meth);
        }
        result = meth.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    setConf(result, conf);
    return result;
}