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:ie.tcd.scss.dsg.particpatory.SampleListFragment.java

private Menu newMenuInstance(Context context) {
    try {//  w w  w .ja v  a 2 s. c  o  m
        Class<?> menuBuilderClass = Class.forName("com.android.internal.view.menu.MenuBuilder");
        Constructor<?> constructor = menuBuilderClass.getDeclaredConstructor(Context.class);
        return (Menu) constructor.newInstance(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.adaptris.http.test.SimpleHttpServer.java

private void addRequestProcessors(Listener l, int threads) throws Exception {
    for (int i = 0; i < threads; i++) {
        Iterator j = processorList.iterator();
        while (j.hasNext()) {
            ProcessorConfig c = (ProcessorConfig) j.next();
            Class clazz = Class.forName(c.getClassName());
            Constructor constructor = clazz
                    .getDeclaredConstructor(new Class[] { String.class, Integer.class, Properties.class });
            RequestProcessor rp = (RequestProcessor) constructor
                    .newInstance(new Object[] { c.getUrl(), new Integer(threads), c.getConfig() });
            l.addRequestProcessor(rp);/* w w w  .  j a v a 2 s  . co m*/
            logR.info("Added " + c.getClassName() + " for " + c.getUrl() + " on " + l);
        }
    }
}

From source file:org.dspace.installer_edm.InstallerManagerCrosswalk.java

/**
 * Se buscan los crosswalk en el directorio packages, se pide el deseado y se instancia la clase.
 * Se llama a su configuracin/*from  w  w  w.j a  v a 2s  .c  om*/
 * @return
 */
public void configure() {
    String suffix = "Crosswalk.java";
    String dirPackages = myInstallerDirPath + fileSeparator + "packages" + fileSeparator;
    File dir = new File(dirPackages);
    String[] files = dir.list(new SuffixFileFilter(suffix));
    for (int i = 0; i < files.length; i++) {
        String crosswalk = files[i].replaceFirst(suffix, "");
        File fileCrosswalk = new File(dirPackages + files[i]);
        if (fileCrosswalk.canRead()) {
            crosswalks.put(crosswalk, fileCrosswalk);
        }
    }
    if (!crosswalks.isEmpty()) {
        String crosswalk = chooseCrosswalk();
        if (crosswalk == null)
            return;
        String installerCrosswalk = "org.dspace.installer_edm.Installer" + crosswalk + "Crosswalk";
        try {
            Class installerCrosswalkClass = Class.forName(installerCrosswalk);
            Constructor ctor = installerCrosswalkClass
                    .getDeclaredConstructor(new Class[] { Integer.class, String.class });
            Object crosswalkClass = (InstallerCrosswalk) ctor.newInstance(new Integer(currentStepGlobal),
                    crosswalk);
            ((InstallerCrosswalk) crosswalkClass).configure();
        } catch (ClassNotFoundException e) {
            showException(e);
        } catch (InstantiationException e) {
            showException(e);
        } catch (IllegalAccessException e) {
            showException(e);
        } catch (InvocationTargetException e) {
            showException(e);
        } catch (NoSuchMethodException e) {
            showException(e);
        }
    }
}

From source file:cn.vlabs.duckling.vwb.service.auth.policy.AuthorizationFileParser.java

private Principal parsePrincipal() 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");
    }/*www .j  a  va 2s  .c  om*/
    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:org.datalorax.populace.core.populate.instance.DefaultConstructorInstanceFactory.java

private <T> Constructor<? extends T> getConstructor(final Class<? extends T> rawType,
        Class<?>... parameterTypes) {
    try {// w  w  w  . j  a v  a  2s .  c  o m
        final Constructor<? extends T> defaultConstructor = rawType.getDeclaredConstructor(parameterTypes);
        defaultConstructor.setAccessible(true);
        return defaultConstructor;
    } catch (NoSuchMethodException e) {
        final Constructor<?>[] constructors = rawType.getDeclaredConstructors();
        throw new PopulatorException(
                "Failed to instantiate type as no viable constructor could be found for type."
                        + " Either add a suitable constructor or consider adding a custom InstanceFactory to handle this type."
                        + "\n\tType: " + rawType + "\n\tRequired constructor arguments: "
                        + (parameterTypes.length == 0 ? "none" : StringUtils.join(parameterTypes, ','))
                        + "\n\tavailable Constructors: "
                        + (constructors.length == 0 ? "none" : StringUtils.join(constructors, ',')),
                e);
    }
}

From source file:org.eyeseetea.malariacare.layout.dashboard.builder.AppSettingsBuilder.java

private ModuleController build(ModuleSettings moduleSettings) {
    Class moduleControllerClass = moduleSettings.getClassController();

    try {//from w  ww.  j a va  2 s  .  c om
        return (ModuleController) moduleControllerClass.getDeclaredConstructor(ModuleSettings.class)
                .newInstance(moduleSettings);
    } catch (Exception ex) {
        Log.e(TAG,
                String.format("Error build module controller with class %s", moduleControllerClass.getName()));
        return null;
    }
}

From source file:org.apache.hadoop.hbase.client.RetryingCallerInterceptorFactory.java

/**
 * This builds the implementation of {@link RetryingCallerInterceptor} that we
 * specify in the conf and returns the same.
 * //from   w ww  .  j a  v a2 s  .  c  o m
 * To use {@link PreemptiveFastFailInterceptor}, set HBASE_CLIENT_ENABLE_FAST_FAIL_MODE to true.
 * HBASE_CLIENT_FAST_FAIL_INTERCEPTOR_IMPL is defaulted to {@link PreemptiveFastFailInterceptor}
 * 
 * @return The factory build method which creates the
 *         {@link RetryingCallerInterceptor} object according to the
 *         configuration.
 */
public RetryingCallerInterceptor build() {
    RetryingCallerInterceptor ret = NO_OP_INTERCEPTOR;
    if (failFast) {
        try {
            Class<?> c = conf.getClass(HConstants.HBASE_CLIENT_FAST_FAIL_INTERCEPTOR_IMPL,
                    PreemptiveFastFailInterceptor.class);
            Constructor<?> constructor = c.getDeclaredConstructor(Configuration.class);
            constructor.setAccessible(true);
            ret = (RetryingCallerInterceptor) constructor.newInstance(conf);
        } catch (Exception e) {
            ret = new PreemptiveFastFailInterceptor(conf);
        }
    }
    LOG.trace("Using " + ret.toString() + " for intercepting the RpcRetryingCaller");
    return ret;
}

From source file:io.gravitee.common.spring.factory.SpringFactoriesLoader.java

@SuppressWarnings("unchecked")
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
        ClassLoader classLoader, Object[] args, Set<String> names) {
    List<T> instances = new ArrayList<>(names.size());
    for (String name : names) {
        try {/*from  w  w  w.ja  va 2s . c o  m*/
            Class<?> instanceClass = ClassUtils.forName(name, classLoader);
            Assert.isAssignable(type, instanceClass);
            Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
            T instance = (T) BeanUtils.instantiateClass(constructor, args);
            ((AbstractApplicationContext) applicationContext).getBeanFactory().autowireBean(instance);
            if (instance instanceof ApplicationContextAware) {
                ((ApplicationContextAware) instance).setApplicationContext(applicationContext);
            }
            instances.add(instance);
        } catch (Throwable ex) {
            throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
        }
    }
    return instances;
}

From source file:org.opendaylight.ovsdb.lib.schema.DatabaseSchema.java

protected <E extends TableSchema<E>> E createTableSchema(Class<E> clazz, TableSchema<E> table) {
    Constructor<E> declaredConstructor = null;
    try {/*from  w  w  w  . j a  v a2s . c om*/
        declaredConstructor = clazz.getDeclaredConstructor(TableSchema.class);
    } catch (NoSuchMethodException e) {
        String message = String
                .format("Class %s does not have public constructor that accepts TableSchema object", clazz);
        throw new IllegalArgumentException(message, e);
    }
    Invokable<E, E> invokable = Invokable.from(declaredConstructor);
    try {
        return invokable.invoke(null, table);
    } catch (Exception e) {
        String message = String.format("Not able to create instance of class %s using public constructor "
                + "that accepts TableSchema object", clazz);
        throw new IllegalArgumentException(message, e);
    }
}

From source file:ch.ksfx.web.pages.activity.ManageActivity.java

public void onValidateFromActivityForm() {
    try {/*  w  w  w.j a  v  a 2s  . c om*/
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        Class clazz = groovyClassLoader.parseClass(activity.getGroovyCode());

        Constructor cons = clazz.getDeclaredConstructor(ObjectLocator.class);
    } catch (Exception e) {
        activityForm.recordError(StacktraceUtil.getStackTrace(e));
    }

    if (activity.getCronSchedule() != null && !activity.getCronSchedule().isEmpty()) {
        try {
            CronExpression cronExpression = new CronExpression(activity.getCronSchedule());
        } catch (Exception e) {
            activityForm.recordError("Cron Schedule not valid");
        }
    }
}