Example usage for java.lang.reflect Constructor newInstance

List of usage examples for java.lang.reflect Constructor newInstance

Introduction

In this page you can find the example usage for java.lang.reflect Constructor newInstance.

Prototype

@CallerSensitive
@ForceInline 
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException 

Source Link

Document

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters.

Usage

From source file:jfs.sync.JFSFileProducerManager.java

/**
 * Registers all factories and sets the default factory.
 *///from ww  w. j av  a 2 s  .c  o  m
@SuppressWarnings("unchecked")
private JFSFileProducerManager() {
    factories = new HashMap<String, JFSFileProducerFactory>();
    Properties p = new Properties();
    ClassLoader classLoader = this.getClass().getClassLoader();
    try {
        p.load(classLoader.getResourceAsStream("producers.properties"));
    } catch (Exception e) {
        log.error("JFSFileProducerManager()", e);
    } // try/catch
    for (Object property : p.keySet()) {
        String className = "" + property;
        if (className.startsWith("jfs.sync.")) {
            if ("on".equals(p.getProperty(className))) {
                try {
                    Class<JFSFileProducerFactory> c = (Class<JFSFileProducerFactory>) classLoader
                            .loadClass(className);
                    Constructor<JFSFileProducerFactory> constructor = c.getConstructor(new Class<?>[0]);
                    JFSFileProducerFactory factory = constructor.newInstance(new Object[0]);
                    String name = factory.getName();
                    factories.put(name, factory);
                } catch (Exception e) {
                    log.error("JFSFileProducerManager()", e);
                } // try/catch
            } // if
        } // if
    } // for
    defaultFactory = factories.get(JFSLocalFileProducerFactory.SCHEME_NAME);
}

From source file:fr.inrialpes.exmo.align.cli.TestGen.java

public void run(String[] args) throws Exception {
    try {//from w  w  w .  j a v  a 2  s.  c  o m
        CommandLine line = parseCommandLine(args);
        if (line == null)
            return; // --help

        outputfilename = fileName; // likely useless

        // Here deal with command specific arguments
        if (line.hasOption('t'))
            methodName = line.getOptionValue('t');
        if (line.hasOption('o'))
            parameters.setProperty("ontoname", line.getOptionValue('o'));
        if (line.hasOption('a'))
            parameters.setProperty("alignname", line.getOptionValue('a'));
        if (line.hasOption('w')) {
            dir = line.getOptionValue('w');
            parameters.setProperty("outdir", dir);
        }
        if (line.hasOption('u')) {
            url = line.getOptionValue('u');
            parameters.setProperty("urlprefix", url); // JE: Danger urlprefix/uriprefix
        }
        String[] argList = line.getArgs();
        if (argList.length > 0) {
            fileName = argList[0];
            parameters.setProperty("filename", fileName);
        } else {
            logger.error("Require the seed ontology filename");
            usage();
            System.exit(-1);
        }
    } catch (ParseException exp) {
        logger.error(exp.getMessage());
        usage();
        System.exit(-1);
    }

    logger.debug(" >>>> {} from {}", methodName, fileName);

    if (methodName == null) { // generate one test
        TestGenerator tg = new TestGenerator();
        // It would certainly be better to initialise the generator with parameters
        tg.setDirPrefix(dir);
        tg.setURLPrefix(url);
        if (parameters.getProperty("ontoname") != null)
            tg.setOntoFilename(parameters.getProperty("ontoname"));
        if (parameters.getProperty("alignname") != null)
            tg.setAlignFilename(parameters.getProperty("alignname"));
        tg.modifyOntology(fileName, (Properties) null, (String) null, parameters);
    } else { // generate a test set
        TestSet tset = null;
        try {
            Class<?> testSetClass = Class.forName(methodName);
            Class<?>[] cparams = {};
            Constructor<?> testSetConstructor = testSetClass.getConstructor(cparams);
            Object[] mparams = {};
            tset = (TestSet) testSetConstructor.newInstance(mparams);
        } catch (Exception ex) {
            logger.error("Cannot create TestSet {}", methodName);
            logger.error("Caught error", ex);
            usage();
            System.exit(-1);
        }
        tset.generate(parameters);
    }
}

From source file:com.jkoolcloud.tnt4j.utils.Utils.java

/**
 * Create object instance based on specific class name and given parameters
 *
 * @param className/* w ww. j  a va 2s  .  com*/
 *            name of the class
 * @param args
 *            arguments to be passed to the constructor
 * @param types
 *            list of parameter types
 *
 * @return instance of the objects specified by the class name
 * @throws Exception
 *             if error creating instance
 */
public static Object createInstance(String className, Object[] args, Class<?>... types) throws Exception {
    if (className == null)
        return null;
    Class<?> classObj = Class.forName(className);
    Constructor<?> ct = classObj.getConstructor(types);
    return ct.newInstance(args);
}

From source file:com.splunk.hunk.input.packet.DnsPcapRecordReader.java

private PcapReader initPcapReader(String className, DataInputStream is) {
    try {/*from w  w  w  .  j av  a 2  s  .c  o  m*/
        @SuppressWarnings("unchecked")
        Class<? extends PcapReader> pcapReaderClass = (Class<? extends PcapReader>) Class.forName(className);
        Constructor<? extends PcapReader> pcapReaderConstructor = pcapReaderClass
                .getConstructor(DataInputStream.class);
        return pcapReaderConstructor.newInstance(is);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.flozano.socialauth.AbstractProvider.java

@Override
public <T> T getPlugin(final Class<T> clazz) throws Exception {
    Class<? extends Plugin> plugin = pluginsMap.get(clazz);
    Constructor<? extends Plugin> cons = plugin.getConstructor(ProviderSupport.class);
    ProviderSupport support = new ProviderSupport(getOauthStrategy());
    Plugin obj = cons.newInstance(support);
    return (T) obj;
}

From source file:dk.netarkivet.common.utils.batch.LoadableFileBatchJob.java

/**
 * Method for initializing the loaded batchjob.
 * @throws IOFailure If the batchjob cannot be loaded.
 *///ww  w  .  java2 s.  c  om
protected void loadBatchJob() throws IOFailure {
    ByteClassLoader singleClassLoader = new ByteClassLoader(fileContents);
    try {
        Class batchClass = singleClassLoader.defineClass();
        if (args.size() == 0) {
            loadedJob = (FileBatchJob) batchClass.newInstance();
        } else {
            // get argument classes (string only).
            Class[] argClasses = new Class[args.size()];
            for (int i = 0; i < args.size(); i++) {
                argClasses[i] = String.class;
            }

            // extract the constructor and instantiate the batchjob.
            Constructor con = batchClass.getConstructor(argClasses);
            loadedJob = (FileBatchJob) con.newInstance(args.toArray());
            log.debug("Loaded batchjob with arguments: '" + args + "'.");
        }
    } catch (InvocationTargetException e) {
        final String msg = "Not allowed to invoke the batchjob '" + fileName + "'.";
        log.warn(msg, e);
        throw new IOFailure(msg, e);
    } catch (NoSuchMethodException e) {
        final String msg = "No constructor for the arguments '" + args + "' can be found for the batchjob '"
                + fileName + "'.";
        log.warn(msg, e);
        throw new IOFailure(msg, e);
    } catch (InstantiationException e) {
        String errMsg = "Cannot instantiate batchjob from byte array";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    } catch (IllegalAccessException e) {
        String errMsg = "Cannot access loaded job from byte array";
        log.warn(errMsg, e);
        throw new IOFailure(errMsg, e);
    }
}

From source file:me.timothy.ddd.quests.QuestManager.java

public void convoEnded(Entity entity, String questName, int[] choiceTree) {
    try {/* w  w w .  j a v a 2 s . c o m*/
        for (Quest quest : acceptedQuests) {
            if (quest.getClass().getName().equals(questName)) {
                quest.onContinued(entity, choiceTree);
                return;
            }
        }
        Class<?> hopefullyTheQuestsClass = Class.forName(questName);
        Constructor<?> constr = hopefullyTheQuestsClass.getConstructor(QuestManager.class);
        Quest quest = (Quest) constr.newInstance(this);
        acceptedQuests.add(quest);
        quest.onApplied(entity, choiceTree);
    } catch (Exception e) {
        logger.printf(Level.WARN, "convo ended with an invalid quest %s", questName);
        logger.catching(e);
    }
}

From source file:de.xwic.appkit.webbase.editors.mappers.MapperFactory.java

/**
 * Create a mapper instance fo the given type.
 * @param mapperId//from  w  w  w  .  j ava2  s.co  m
 * @return
 * @throws EditorConfigurationException 
 */
@SuppressWarnings("rawtypes")
public PropertyMapper<IControl> createMapper(String mapperId, EntityDescriptor descriptor)
        throws EditorConfigurationException {

    Class<? extends PropertyMapper<?>> clazz = knownMappers.get(mapperId);
    if (clazz == null) {
        throw new IllegalArgumentException("A mapper with the id '" + mapperId + "' is unknown.");
    }

    try {
        Constructor<? extends PropertyMapper> constructor = clazz.getConstructor(EntityDescriptor.class);
        @SuppressWarnings("unchecked")
        PropertyMapper<IControl> mapper = constructor.newInstance(descriptor);
        return mapper;

    } catch (Exception e) {
        throw new EditorConfigurationException(
                "Cannot create mapper id '" + mapperId + "' (" + clazz.getName() + ")", e);
    }

}

From source file:com.processpuzzle.fundamental_types.uniqueidentifier.domain.PrefixedIncNumberedIdFactory.java

@SuppressWarnings("unchecked")
private UniqueIdentifier generateUniqueIdentifierByType(String idType, String identifier) {
    UniqueIdentifier uniqueIdentifier = null;
    if (idType != null && !idType.equals("")) {
        Class identifierClass = null;
        try {//w  ww .  java 2s  . c  o m
            identifierClass = Class.forName(idType);
            try {
                Class[] argumentClasses = new Class[] { String.class };
                Object[] arguments = new Object[] { identifier };
                Constructor identifierConstructor = identifierClass.getConstructor(argumentClasses);
                uniqueIdentifier = (UniqueIdentifier) identifierConstructor.newInstance(arguments);
            } catch (SecurityException e) {
                throw new UniqueIdentifierInstantiationException(identifierClass.getName(), identifier);
            } catch (NoSuchMethodException e) {
                throw new UniqueIdentifierInstantiationException(identifierClass.getName(), identifier);
            } catch (IllegalArgumentException e) {
                throw new UniqueIdentifierInstantiationException(identifierClass.getName(), identifier);
            } catch (InvocationTargetException e) {
                throw new UniqueIdentifierInstantiationException(identifierClass.getName(), identifier);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    return uniqueIdentifier;

}

From source file:com.glaf.core.util.ReflectUtils.java

public static Object newInstance(final Constructor<?> cstruct, final Object[] args) {
    boolean flag = cstruct.isAccessible();
    try {/*from   w ww. j  a  v a2s  .c om*/
        cstruct.setAccessible(true);
        Object result = cstruct.newInstance(args);
        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        cstruct.setAccessible(flag);
    }
}