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 void main(String[] args) throws Exception {

    MyClass cls = new MyClass();
    Class c = cls.getClass();

    // constructor with arguments as Double and Long
    Class[] cArg = new Class[2];
    cArg[0] = Double.class;
    cArg[1] = Long.class;
    Constructor ct = c.getDeclaredConstructor(cArg);
    System.out.println("Constructor = " + ct.toString());

}

From source file:com.atilika.kuromoji.benchmark.Benchmark.java

public static void main(String[] args) throws IOException {
    Options options = new Options();
    options.addOption("h", "help", false, "Display this help message and exit");
    options.addOption("t", "tokenizer", true, "Tokenizer class to use");
    options.addOption("u", "user-dictionary", true, "Optional user dictionary filename to use");
    options.addOption("c", "count", true, "Number of documents ot process (Default: 0, which means all");
    //        options.addOption("v", "validation-input", true, "Validation filename");
    options.addOption("o", "output", true,
            "Output filename.  If unset, segmentation is done, but the result is discarded");
    options.addOption("n", "n-best", true, "The number of tokenizations to get per input");
    options.addOption(null, "benchmark-output", true, "Benchmark metrics output filename filename");

    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = null;/*from   w  w w. j a  v a2  s.  c o m*/
    try {
        commandLine = parser.parse(options, args);

        args = commandLine.getArgs();

        if (args.length != 1) {
            throw new ParseException("A single input filename is required");
        }
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        usage(options);
    }

    String inputFilename = args[0];

    String className = commandLine.getOptionValue("t", "com.atilika.kuromoji.ipadic.Tokenizer");

    className += "$Builder";

    String userDictionaryFilename = commandLine.getOptionValue("u");

    TokenizerBase tokenizer = null;
    try {
        Class clazz = Class.forName(className);

        // Make builder
        Object builder = clazz.getDeclaredConstructor(null).newInstance();

        // Set user dictionary
        if (userDictionaryFilename != null) {
            builder.getClass().getMethod("userDictionary", String.class).invoke(builder,
                    userDictionaryFilename);
        }

        // Build tokenizer
        tokenizer = (TokenizerBase) builder.getClass().getMethod("build").invoke(builder);

    } catch (Exception e) {
        System.err.println("Could not create tokenizer. Got " + e);
        e.printStackTrace();
        System.exit(1);
    }

    File outputFile = null;
    String outputFilename = commandLine.getOptionValue("o");

    if (outputFilename != null) {
        outputFile = new File(outputFilename);
    }

    File statisticsFile = null;
    String statisticsFilename = commandLine.getOptionValue("benchmark-output");

    if (statisticsFilename != null) {
        statisticsFile = new File(statisticsFilename);
    }

    long count = Long.parseLong(commandLine.getOptionValue("c", "0"));

    int nbest = Integer.parseInt(commandLine.getOptionValue("n", "1"));

    Benchmark benchmark = new Builder().tokenizer(tokenizer).inputFile(new File(inputFilename))
            .outputFile(outputFile).outputStatisticsFile(statisticsFile).setOutputStatistiscs(true).count(count)
            .nbest(nbest).build();

    benchmark.benchmark();
}

From source file:Main.java

static void initReflection() {
    try {/* w w  w  .jav a2s.  c o m*/

        // lightweight dispatcher
        dispatcherField = Container.class.getDeclaredField("dispatcher");
        dispatcherField.setAccessible(true);

        Class<?> dispatcherCls = Class.forName("java.awt.LightweightDispatcher");
        newLightweightDispatcher = dispatcherCls.getDeclaredConstructor(new Class[] { Container.class });
        newLightweightDispatcher.setAccessible(true);

        dispatchMethod = dispatcherCls.getDeclaredMethod("dispatchEvent", AWTEvent.class);
        dispatchMethod.setAccessible(true);

        enableEvents = dispatcherCls.getDeclaredMethod("enableEvents", new Class[] { long.class });
        enableEvents.setAccessible(true);

    } catch (Exception ex) {

        System.err.println(ex);

        InternalError err = new InternalError();
        err.initCause(ex);
        throw err;
    }
}

From source file:org.apache.tajo.ws.rs.resources.outputs.RestOutputFactory.java

public static AbstractStreamingOutput get(String mimeType, NonForwardQueryResultScanner scanner, Integer count,
        Integer startOffset) {//from   w w w . j  av  a2s.co m
    AbstractStreamingOutput output = null;
    try {
        if (restOutputClasses.containsKey(mimeType)) {
            String className = (String) restOutputClasses.get(mimeType);
            Class<?> clazz = Class.forName(className);
            output = (AbstractStreamingOutput) clazz
                    .getDeclaredConstructor(
                            new Class[] { NonForwardQueryResultScanner.class, Integer.class, Integer.class })
                    .newInstance(scanner, count, startOffset);
        } else {
            output = new CSVStreamingOutput(scanner, count, startOffset);
        }
    } catch (Exception eh) {
        LOG.error(eh);
    }

    return output;
}

From source file:Main.java

public static <T extends Object> T newInstance(Class<T> cl, Object... args) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException, InstantiationException {
    Constructor<T> constructor = cl.getDeclaredConstructor(new Class[0]);
    boolean accessible = constructor.isAccessible();
    constructor.setAccessible(true);/* ww  w. ja  v  a 2s .c o  m*/
    T t = constructor.newInstance(args);
    constructor.setAccessible(accessible);
    return t;
}

From source file:Main.java

public static <T> Constructor<T> findConstructor(Class<T> paramClass, boolean paramBoolean) {
    Constructor localConstructor;
    try {//from   w w  w  .j av  a2 s .c o 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:marshalsec.gadgets.ToStringUtil.java

public static Object makeJohnzonToStringTrigger(Object o) throws Exception {
    Class<?> clz = Class.forName("org.apache.johnzon.core.JsonObjectImpl"); //$NON-NLS-1$
    Constructor<?> dec = clz.getDeclaredConstructor(Map.class);
    dec.setAccessible(true);/*w w w.  j a  va  2 s.  co m*/
    HashMap<Object, Object> m = new HashMap<>();
    Object jo = dec.newInstance(m);
    m.put(o, o);
    XString toStringTrig = new XString("");
    return Arrays.asList(jo, JDKUtil.makeMap(jo, toStringTrig));
}

From source file:com.hortonworks.minicluster.util.ReflectionUtils.java

/**
 * /*from   w  ww  . ja  va  2 s  .  co  m*/
 * @param className
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getInvocableConstructor(String className, Class<?>... parameterTypes) {
    try {
        Class<?> clazz = Class.forName(className);
        Constructor<T> constructor = (Constructor<T>) clazz.getDeclaredConstructor(parameterTypes);
        constructor.setAccessible(true);
        return constructor;
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to create instance of " + className + " using default constructor", e);
    }
}

From source file:org.kul.xml.ADocument.java

public static ADocument create(final File file, final Class<? extends ADocument> docType)
        throws DocumentException {
    Throwable ex = null;/*w  w  w  .j  a  va 2s. c om*/
    try {
        return docType.getDeclaredConstructor(File.class).newInstance(file);
    } catch (InstantiationException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (IllegalAccessException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (IllegalArgumentException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (InvocationTargetException e) {
        ex = e.getCause();
    } catch (NoSuchMethodException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    } catch (SecurityException e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }

    if (ex != null) {
        if (DocumentException.class.isAssignableFrom(ex.getClass()))
            throw (DocumentException) ex;
    }

    throw new DocumentException("XML Document creation failed, see stack trace");
}

From source file:org.alfresco.util.ReflectionHelper.java

/**
 * Constructs a new object for the given class name and with the given
 * arguments.  The arguments must be specified in terms of their Class[]
 * types and their Object[] values.//from  w ww .j a  v a  2  s. c  o  m
 * 
 * Example:
 * 
 *   String s = newObject("java.lang.String", new Class[] { String.class},
 *              new String[] { "test"});
 *              
 * is equivalent to:
 * 
 *   String s = new String("test");
 * 
 * If an exception occurs during construction, null is returned.
 * 
 * All exceptions are written to the Log instance for this class.
        
 * @param className String
 * @param argTypes Class[]
 * @param args Object[]
 * @return Object
 */
public static Object newObject(String className, Class[] argTypes, Object[] args) {
    /**
     * We have some mercy here - if they called and did not pass in any
     * arguments, then we will call through to the pure newObject() method.
     */
    if (args == null || args.length == 0) {
        return newObject(className);
    }

    /**
     * Try to build the object
     * 
     * If an exception occurs, we log it and return null.
     */
    Object o = null;
    try {
        // base class
        Class clazz = Class.forName(className);

        Constructor c = clazz.getDeclaredConstructor(argTypes);
        o = c.newInstance(args);
    } catch (ClassNotFoundException cnfe) {
        logger.debug(cnfe);
    } catch (InstantiationException ie) {
        logger.debug(ie);
    } catch (IllegalAccessException iae) {
        logger.debug(iae);
    } catch (NoSuchMethodException nsme) {
        logger.debug(nsme);
    } catch (InvocationTargetException ite) {
        logger.debug(ite);
    }
    return o;
}