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:com.google.gdt.eclipse.designer.util.GwtInvocationEvaluatorInterceptor.java

private static Object createDateLabel(ClassInstanceCreation expression, Constructor<?> actualConstructor,
        Object[] arguments) throws Exception {
    Object valueLabel = actualConstructor.newInstance(arguments);
    setValueLabelText(valueLabel, "12/31/2010");
    return valueLabel;
}

From source file:TypeUtil.java

/** Convert String value to instance.
 * @param type The class of the instance, which may be a primitive TYPE field.
 * @param value The value as a string./*from   w  w w.j  a  v  a2 s . c  om*/
 * @return The value as an Object.
 */
public static Object valueOf(Class type, String value) {
    try {
        if (type.equals(java.lang.String.class))
            return value;

        Method m = (Method) class2Value.get(type);
        if (m != null)
            return m.invoke(null, new Object[] { value });

        if (type.equals(java.lang.Character.TYPE) || type.equals(java.lang.Character.class))
            return new Character(value.charAt(0));

        Constructor c = type.getConstructor(stringArg);
        return c.newInstance(new Object[] { value });
    } catch (NoSuchMethodException e) {
        // LogSupport.ignore(log,e);
    } catch (IllegalAccessException e) {
        // LogSupport.ignore(log,e);
    } catch (InstantiationException e) {
        // LogSupport.ignore(log,e);
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof Error)
            throw (Error) (e.getTargetException());
        // LogSupport.ignore(log,e);
    }
    return null;
}

From source file:com.github.jinahya.codec.commons.AbstractEncoderProxy.java

/**
 * Creates a new proxy instance.//from   w ww.j av  a2 s  .c  o  m
 *
 * @param <P> proxy type parameter
 * @param <T> encoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param encoderType encoder type
 * @param encoder encoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractEncoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> encoderType, final T encoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (encoderType == null) {
        throw new NullPointerException("encoderType");
    }

    if (encoder == null) {
        //throw new NullPointerException("encoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(encoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(encoder));
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:com.google.gdt.eclipse.designer.util.GwtInvocationEvaluatorInterceptor.java

private static Object createNumberLabel(ClassInstanceCreation expression, Constructor<?> actualConstructor,
        Object[] arguments) throws Exception {
    Object valueLabel = actualConstructor.newInstance(arguments);
    // prepare text to show
    String text;//from  w  ww.j a  v a 2s.c o  m
    {
        ITypeBinding creationBinding = AstNodeUtils.getTypeBinding(expression);
        ITypeBinding typeBinding = AstNodeUtils.getTypeBindingArgument(creationBinding,
                "com.google.gwt.user.client.ui.NumberLabel", 0);
        String typeName = AstNodeUtils.getFullyQualifiedName(typeBinding, false);
        text = MessageFormat.format("NumberLabel<{0}>", CodeUtils.getShortClass(typeName));
    }
    // set text
    setValueLabelText(valueLabel, text);
    return valueLabel;
}

From source file:com.github.jinahya.codec.commons.AbstractDecoderProxy.java

/**
 * Creates a new proxy instance.//from   www.  ja v a 2 s  .com
 *
 * @param <P> proxy type parameter
 * @param <T> decoder type parameter
 * @param loader class loader
 * @param interfaces interfaces
 * @param proxyType proxy type
 * @param decoderType decoder type
 * @param decoder decoder
 *
 * @return a new proxy instance.
 */
protected static <P extends AbstractDecoderProxy<T>, T> Object newInstance(final ClassLoader loader,
        final Class<?>[] interfaces, final Class<P> proxyType, final Class<T> decoderType, final T decoder) {

    if (loader == null) {
        throw new NullPointerException("loader");
    }

    if (interfaces == null) {
        throw new NullPointerException("interfaces");
    }

    if (proxyType == null) {
        throw new NullPointerException("proxyType");
    }

    if (decoderType == null) {
        throw new NullPointerException("decoderType");
    }

    if (decoder == null) {
        //throw new NullPointerException("decoder");
    }

    try {
        final Constructor<P> constructor = proxyType.getDeclaredConstructor(decoderType);
        if (!constructor.isAccessible()) {
            constructor.setAccessible(true);
        }
        try {
            return Proxy.newProxyInstance(loader, interfaces, constructor.newInstance(decoder));
        } catch (final InstantiationException ie) {
            throw new RuntimeException(ie);
        } catch (final IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (final InvocationTargetException ite) {
            throw new RuntimeException(ite);
        }
    } catch (final NoSuchMethodException nsme) {
        throw new RuntimeException(nsme);
    }
}

From source file:com.inmobi.messaging.consumer.databus.AbstractMessagingDatabusConsumer.java

public static CheckpointProvider createCheckpointProvider(String checkpointProviderClassName,
        String chkpointDir) {/*w  w  w .  j  a  va2s . c o m*/
    CheckpointProvider chkProvider = null;
    try {
        Class<?> clazz = Class.forName(checkpointProviderClassName);
        Constructor<?> constructor = clazz.getConstructor(String.class);
        chkProvider = (CheckpointProvider) constructor.newInstance(new Object[] { chkpointDir });
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Could not create checkpoint provider " + checkpointProviderClassName, e);
    }
    return chkProvider;
}

From source file:jp.sf.fess.solr.plugin.suggest.util.SolrConfigUtil.java

public static List<SuggestFieldInfo> getSuggestFieldInfoList(final SuggestUpdateConfig config) {
    final List<SuggestFieldInfo> list = new ArrayList<SuggestFieldInfo>();

    for (final SuggestUpdateConfig.FieldConfig fieldConfig : config.getFieldConfigList()) {
        try {/*from   w  w w. j a va 2 s  .  c o m*/
            final List<String> fieldNameList = Arrays.asList(fieldConfig.getTargetFields());
            final SuggestUpdateConfig.TokenizerConfig tokenizerConfig = fieldConfig.getTokenizerConfig();

            //create tokenizerFactory
            TokenizerFactory tokenizerFactory = null;
            if (tokenizerConfig != null) {
                final Class<?> cls = Class.forName(tokenizerConfig.getClassName());
                final Constructor<?> constructor = cls.getConstructor(Map.class);
                tokenizerFactory = (TokenizerFactory) constructor.newInstance(tokenizerConfig.getArgs());
                try {
                    final Class[] params = new Class[] { ResourceLoader.class };
                    final Method inform = cls.getDeclaredMethod("inform", params);
                    final Object[] args = new Object[] { new FilesystemResourceLoader() };
                    inform.invoke(tokenizerFactory, args);
                } catch (final NoSuchMethodException e) {
                    //ignore
                } catch (final Exception e) {
                    logger.warn("Failed to execute inform of tokenizer.", e);
                }
            }

            //create converter
            final SuggestIntegrateConverter suggestIntegrateConverter = new SuggestIntegrateConverter();
            for (final SuggestUpdateConfig.ConverterConfig converterConfig : fieldConfig
                    .getConverterConfigList()) {
                final SuggestReadingConverter suggestReadingConverter = SuggestUtil
                        .createConverter(converterConfig.getClassName(), converterConfig.getProperties());
                suggestIntegrateConverter.addConverter(suggestReadingConverter);
            }
            if (tokenizerFactory != null) {
                suggestIntegrateConverter.setTokenizerFactory(tokenizerFactory);
            }
            suggestIntegrateConverter.start();

            //create normalizer
            final SuggestIntegrateNormalizer suggestIntegrateNormalizer = new SuggestIntegrateNormalizer();
            for (final SuggestUpdateConfig.NormalizerConfig normalizerConfig : fieldConfig
                    .getNormalizerConfigList()) {
                final SuggestNormalizer suggestNormalizer = SuggestUtil
                        .createNormalizer(normalizerConfig.getClassName(), normalizerConfig.getProperties());
                suggestIntegrateNormalizer.addNormalizer(suggestNormalizer);
            }
            suggestIntegrateNormalizer.start();

            final SuggestFieldInfo suggestFieldInfo = new SuggestFieldInfo(fieldNameList, tokenizerFactory,
                    suggestIntegrateConverter, suggestIntegrateNormalizer);
            list.add(suggestFieldInfo);
        } catch (final Exception e) {
            throw new FessSuggestException(
                    "Failed to create Tokenizer." + fieldConfig.getTokenizerConfig().getClassName(), e);
        }
    }
    return list;
}

From source file:com.fer.hr.olap.util.ObjectUtil.java

private static SaikuLevel convert(Level level) {
    Checker c = new Checker();
    try {//from ww w  . j av  a2 s .  c  om
        try {
            Class.forName("mondrian.olap4j.MondrianOlap4jLevelExtend");
            //Class.forName("bi.meteorite.CheckClass");
            Class<LevelInterface> _tempClass = (Class<LevelInterface>) Class
                    .forName("mondrian.olap4j.MondrianOlap4jLevelExtend");
            if (c.checker(level)) {
                Constructor<LevelInterface> ctor = _tempClass
                        .getDeclaredConstructor(org.olap4j.metadata.Level.class);
                LevelInterface test = ctor.newInstance(level);
                HashMap<String, String> m = null;
                if (test.getAnnotations() != null) {
                    m = new HashMap<>();
                    for (Map.Entry<String, Annotation> entry : test.getAnnotations().entrySet()) {
                        m.put(entry.getKey(), (String) entry.getValue().getValue());
                    }
                }
                return new SaikuLevel(test.getName(), test.getUniqueName(), test.getCaption(),
                        test.getDescription(), test.getDimension().getUniqueName(),
                        test.getHierarchy().getUniqueName(), test.isVisible(), test.getLevelType().toString(),
                        m);
            } else {
                return new SaikuLevel(level.getName(), level.getUniqueName(), level.getCaption(),
                        level.getDescription(), level.getDimension().getUniqueName(),
                        level.getHierarchy().getUniqueName(), level.isVisible(), null, null);
            }
        } catch (ClassNotFoundException e) {
            return new SaikuLevel(level.getName(), level.getUniqueName(), level.getCaption(),
                    level.getDescription(), level.getDimension().getUniqueName(),
                    level.getHierarchy().getUniqueName(), level.isVisible(), null, null);
        }

    } catch (Exception e) {
        throw new SaikuServiceException("Cannot convert level: " + level, e);
    }
}

From source file:com.qmetry.qaf.automation.ui.UiDriverFactory.java

private static WebDriver getDriverObj(Class<? extends WebDriver> of, Capabilities capabilities, String urlStr) {
    try {/*from   w w  w.j a v  a 2s  . co  m*/
        Constructor<? extends WebDriver> constructor = of.getConstructor(Capabilities.class);
        return constructor.newInstance(capabilities);
    } catch (Exception e) {
        if (e.getCause() != null && e.getCause() instanceof WebDriverException) {
            throw (WebDriverException) e.getCause();
        }
        try {
            return of.newInstance();
        } catch (Exception e1) {
            try {

                Constructor<? extends WebDriver> constructor = of.getConstructor(URL.class, Capabilities.class);

                return constructor.newInstance(new URL(urlStr), capabilities);
            } catch (InvocationTargetException e2) {
                throw new WebDriverException(e2);
            } catch (InstantiationException e2) {
                throw new WebDriverException(e2);
            } catch (IllegalAccessException e2) {
                throw new WebDriverException(e2);
            } catch (IllegalArgumentException e2) {
                throw new WebDriverException(e2);
            } catch (MalformedURLException e2) {
                throw new WebDriverException(e2);
            } catch (NoSuchMethodException e2) {
                throw new WebDriverException(e2);
            } catch (SecurityException e2) {
                throw new WebDriverException(e2);
            }
        }
    }
}

From source file:org.exist.xquery.modules.jfreechart.JFreeChartFactory.java

private static void setCategoryItemLabelGenerator(JFreeChart chart, Configuration config)
        throws XPathException {
    String className = config.getCategoryItemLabelGeneratorClass();
    CategoryItemLabelGenerator generator = null;

    if (className != null) {
        try {//from   w w  w  . j  a va 2  s.  c  o  m
            Class generatorClass = Class.forName(className);

            Class[] argsClass = new Class[] { String.class, NumberFormat.class };
            String param = config.getCategoryItemLabelGeneratorParameter();
            NumberFormat fmt = new DecimalFormat(config.getCategoryItemLabelGeneratorNumberFormat());
            Object[] args = new Object[] { param, fmt };

            Constructor argsConstructor = generatorClass.getConstructor(argsClass);

            generator = (CategoryItemLabelGenerator) argsConstructor.newInstance(args);
        } catch (Exception e) {
            throw (new XPathException(
                    "Cannot instantiate CategoryItemLabelGeneratorClass: " + className + ", exception: " + e));
        }

        if (chart.getPlot() instanceof SpiderWebPlot) {
            ((SpiderWebPlot) chart.getPlot()).setLabelGenerator(generator);
        } else {
            CategoryItemRenderer renderer = ((CategoryPlot) chart.getPlot()).getRenderer();

            renderer.setBaseItemLabelGenerator(generator);

            renderer.setItemLabelsVisible(true);
        }
    }
}