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:org.apache.tajo.storage.StorageManager.java

/**
 * Returns the proper StorageManager instance according to the storeType
 *
 * @param tajoConf Tajo system property.
 * @param storeType Storage type//w w  w .ja va  2  s .co m
 * @param managerKey Key that can identify each storage manager(may be a path)
 * @return
 * @throws java.io.IOException
 */
private static synchronized StorageManager getStorageManager(TajoConf tajoConf, StoreType storeType,
        String managerKey) throws IOException {

    String typeName;
    switch (storeType) {
    case HBASE:
        typeName = "hbase";
        break;
    default:
        typeName = "hdfs";
    }

    synchronized (storageManagers) {
        String storeKey = typeName + "_" + managerKey;
        StorageManager manager = storageManagers.get(storeKey);

        if (manager == null) {
            Class<? extends StorageManager> storageManagerClass = tajoConf.getClass(
                    String.format("tajo.storage.manager.%s.class", typeName), null, StorageManager.class);

            if (storageManagerClass == null) {
                throw new IOException("Unknown Storage Type: " + typeName);
            }

            try {
                Constructor<? extends StorageManager> constructor = (Constructor<? extends StorageManager>) CONSTRUCTOR_CACHE
                        .get(storageManagerClass);
                if (constructor == null) {
                    constructor = storageManagerClass
                            .getDeclaredConstructor(new Class<?>[] { StoreType.class });
                    constructor.setAccessible(true);
                    CONSTRUCTOR_CACHE.put(storageManagerClass, constructor);
                }
                manager = constructor.newInstance(new Object[] { storeType });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            manager.init(tajoConf);
            storageManagers.put(storeKey, manager);
        }

        return manager;
    }
}

From source file:org.mitre.ccv.weka.CompositionCompositionVectorClassifiers.java

/** 
 * Returns a classifier loaded from the given saved model.
 * @param <T>/*from  w w  w . j ava2  s . c o  m*/
 * @param theClassifier
 * @param inputFile
 */
@SuppressWarnings("unchecked")
private <T> T loadClassifierInstanceFromModel(Class<T> theClassifier, String inputFile) {
    T result;
    try {
        Constructor<T> meth = theClassifier.getDeclaredConstructor(new Class[] { String.class });
        //meth.setAccessible(true);
        result = meth.newInstance(inputFile);
    } catch (Exception e) {
        LOG.fatal("Error in loading a classifier from a model!");
        throw new RuntimeException(e);
    }
    return result;
}

From source file:com.mymita.vaadlets.VaadletsBuilder.java

private com.vaadin.ui.Component createComponent(final com.mymita.vaadlets.core.Component vaadletComponent)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    if (vaadletComponent instanceof com.mymita.vaadlets.addon.CodeMirror) {
        // TODO build tag handler to adapt custom tags
        final com.mymita.vaadlets.addon.CodeMirror cm = (com.mymita.vaadlets.addon.CodeMirror) vaadletComponent;
        final Class<?> codeMirrorComponentClass = Class.forName("org.vaadin.codemirror.CodeMirror");
        try {//from   w  ww.  j av a2  s.  c om
            final Constructor<?> constructor = codeMirrorComponentClass.getDeclaredConstructor(String.class);
            final CodeMirror result = (CodeMirror) constructor.newInstance(cm.getCaption());
            result.setCodeStyle(VaadinUtils.codeMirrorCodeStyleOf(cm.getCodeStyle()));
            result.setShowLineNumbers(cm.isShowLineNumbers());
            return result;
        } catch (NoSuchMethodException | SecurityException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new IllegalArgumentException(
                    format("Can't create vaadin component for vaadlets component '%s'", vaadletComponent), e);
        }
    }
    String vaadinComponentClassName = null;
    if (vaadletComponent instanceof com.mymita.vaadlets.ui.PopupView) {
        // TODO build tag handler to adapt custom tags
        final com.mymita.vaadlets.ui.PopupView popupView = (com.mymita.vaadlets.ui.PopupView) vaadletComponent;
        final String small = popupView.getSmall();
        final com.mymita.vaadlets.core.Component large = ((JAXBElement<com.mymita.vaadlets.core.Component>) popupView
                .getLarge().getContent().get(0)).getValue();
        LOG.debug(format("Create vaadin component '%s' with small '%s' and large '%s'",
                vaadinComponentClassName, small, large));
        return new PopupView(small, createVaadinComponentWithChildren(large));
    }
    vaadinComponentClassName = "com.vaadin.ui." + vaadletComponent.getClass().getSimpleName();
    LOG.debug(format("Create vaadin component '%s'", vaadinComponentClassName));
    return (com.vaadin.ui.Component) Class.forName(vaadinComponentClassName).newInstance();
}

From source file:org.mitre.ccv.weka.CompositionCompositionVectorClassifiers.java

/**
 * Returns a classifier loaded with the given dataset.
 * @param <T>/*ww  w.  ja  va2 s. c  om*/
 * @param theClassifier
 * @param inputFile
 */
@SuppressWarnings("unchecked")
private <T> T loadClassifierInstanceFromData(Class<T> theClassifier, JSONObject jsonDataSet) {
    T result;
    Constructor<T> meth;
    try {
        meth = theClassifier.getDeclaredConstructor(new Class[] { JSONObject.class });
    } catch (Exception e) {
        LOG.fatal("Error in getting getting a classifier for JSON data!");
        throw new RuntimeException(e);
    }
    try {
        result = meth.newInstance(jsonDataSet);
    } catch (Exception e) {
        // ideally would like to catch JSONException but we can't do that via reflection (not thrown directly)
        LOG.fatal("Error in loading JSON data for classifier (malformed JSON)!");
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.apache.hadoop.hbase.index.covered.CoveredColumnsIndexBuilder.java

@Override
public void setup(RegionCoprocessorEnvironment env) throws IOException {
    this.env = env;
    // setup the phoenix codec. Generally, this will just be in standard one, but abstracting here
    // so we can use it later when generalizing covered indexes
    Configuration conf = env.getConfiguration();
    Class<? extends IndexCodec> codecClass = conf.getClass(CODEC_CLASS_NAME_KEY, null, IndexCodec.class);
    try {//ww w .  ja v  a 2s . c o  m
        Constructor<? extends IndexCodec> meth = codecClass.getDeclaredConstructor(new Class[0]);
        meth.setAccessible(true);
        this.codec = meth.newInstance();
        this.codec.initialize(env);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }

    this.localTable = new LocalTable(env);
}

From source file:org.apache.tajo.master.rm.TajoResourceManager.java

protected synchronized AbstractQueryScheduler loadScheduler(String schedulerClassName) throws Exception {
    Class<? extends AbstractQueryScheduler> schedulerClass;
    if (SCHEDULER_CLASS_CACHE.containsKey(schedulerClassName)) {
        schedulerClass = SCHEDULER_CLASS_CACHE.get(schedulerClassName);
    } else {// w  ww. ja v a  2 s. c om
        schedulerClass = (Class<? extends AbstractQueryScheduler>) Class.forName(schedulerClassName);
        SCHEDULER_CLASS_CACHE.put(schedulerClassName, schedulerClass);
    }

    Constructor<? extends AbstractQueryScheduler> constructor = schedulerClass
            .getDeclaredConstructor(new Class[] { TajoMaster.MasterContext.class });
    constructor.setAccessible(true);

    return constructor.newInstance(new Object[] { masterContext });
}

From source file:com.msopentech.odatajclient.engine.communication.request.ODataRequestImpl.java

/**
 * Gets an empty response that can be initialized by a stream.
 * <p>//from w w w  .j a v a  2s.  c o m
 * This method has to be used to build response items about a batch request.
 *
 * @param <V> ODataResppnse type.
 * @return empty OData response instance.
 */
@SuppressWarnings("unchecked")
public <V extends ODataResponse> V getResponseTemplate() {

    for (Class<?> clazz : this.getClass().getDeclaredClasses()) {
        if (ODataResponse.class.isAssignableFrom(clazz)) {
            try {
                final Constructor<?> constructor = clazz.getDeclaredConstructor(this.getClass());
                constructor.setAccessible(true);
                return (V) constructor.newInstance(this);
            } catch (Exception e) {
                LOG.error("Error retrieving response class template instance", e);
            }
        }
    }

    throw new IllegalStateException("No response class template has been found");
}

From source file:org.apache.ranger.audit.provider.AuditProviderFactory.java

private AuditHandler getProviderFromConfig(Properties props, String propPrefix, String providerName,
        AuditHandler consumer) {//  ww  w  . j  ava  2 s  .  co m
    AuditHandler provider = null;
    String className = MiscUtil.getStringProperty(props, propPrefix + "." + BaseAuditHandler.PROP_CLASS_NAME);
    if (className != null && !className.isEmpty()) {
        try {
            Class<?> handlerClass = Class.forName(className);
            if (handlerClass.isAssignableFrom(AuditQueue.class)) {
                // Queue class needs consumer
                handlerClass.getDeclaredConstructor(AuditHandler.class).newInstance(consumer);
            } else {
                provider = (AuditHandler) Class.forName(className).newInstance();
            }
        } catch (Exception e) {
            LOG.fatal("Can't instantiate audit class for providerName=" + providerName + ", className="
                    + className + ", propertyPrefix=" + propPrefix, e);
        }
    } else {
        if (providerName.equals("file")) {
            provider = new FileAuditDestination();
        } else if (providerName.equalsIgnoreCase("hdfs")) {
            provider = new HDFSAuditDestination();
        } else if (providerName.equals("solr")) {
            provider = new SolrAuditDestination();
        } else if (providerName.equals("kafka")) {
            provider = new KafkaAuditProvider();
        } else if (providerName.equals("db")) {
            provider = new DBAuditDestination();
        } else if (providerName.equals("log4j")) {
            provider = new Log4JAuditDestination();
        } else if (providerName.equals("batch")) {
            provider = new AuditBatchQueue(consumer);
        } else if (providerName.equals("async")) {
            provider = new AuditAsyncQueue(consumer);
        } else {
            LOG.error("Provider name doesn't have any class associated with it. providerName=" + providerName
                    + ", propertyPrefix=" + propPrefix);
        }
    }
    if (provider != null && provider instanceof AuditQueue) {
        if (consumer == null) {
            LOG.fatal("consumer can't be null for AuditQueue. queue=" + provider.getName() + ", propertyPrefix="
                    + propPrefix);
            provider = null;
        }
    }
    return provider;
}

From source file:org.springframework.aop.framework.ObjenesisCglibAopProxy.java

@Override
@SuppressWarnings("unchecked")
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    Class<?> proxyClass = enhancer.createClass();
    Object proxyInstance = null;/* w w  w.  j  a v  a2 s .co  m*/

    if (objenesis.isWorthTrying()) {
        try {
            proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
        } catch (Throwable ex) {
            logger.debug("Unable to instantiate proxy using Objenesis, "
                    + "falling back to regular proxy construction", ex);
        }
    }

    if (proxyInstance == null) {
        // Regular instantiation via default constructor...
        try {
            Constructor<?> ctor = (this.constructorArgs != null
                    ? proxyClass.getDeclaredConstructor(this.constructorArgTypes)
                    : proxyClass.getDeclaredConstructor());
            ReflectionUtils.makeAccessible(ctor);
            proxyInstance = (this.constructorArgs != null ? ctor.newInstance(this.constructorArgs)
                    : ctor.newInstance());
        } catch (Throwable ex) {
            throw new AopConfigException("Unable to instantiate proxy using Objenesis, "
                    + "and regular proxy instantiation via default constructor fails as well", ex);
        }
    }

    ((Factory) proxyInstance).setCallbacks(callbacks);
    return proxyInstance;
}

From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java

/**
 * Computes CCN for a method.//from   w  w w .  j  a  v a  2s.c  o  m
 *
 * @param classData        class data for the class which contains the method to compute CCN for
 * @param methodName       the name of the method to compute CCN for
 * @param methodDescriptor the descriptor of the method to compute CCN for
 * @return CCN for the method
 * @throws NullPointerException if <code>classData</code> is <code>null</code>
 */
public int getCCNForMethod(ClassData classData, String methodName, String methodDescriptor) {
    if (!calculateMethodComplexity) {
        return 0;
    }

    Validate.notNull(classData, "classData must not be null");
    Validate.notNull(methodName, "methodName must not be null");
    Validate.notNull(methodDescriptor, "methodDescriptor must not be null");

    int complexity = 0;
    List<FunctionMetric> methodMetrics = getFunctionMetricsForSingleFile(classData.getSourceFileName());

    // golden method = method for which we need ccn
    String goldenMethodName = methodName;
    boolean isConstructor = false;
    if (goldenMethodName.equals("<init>")) {
        isConstructor = true;
        goldenMethodName = classData.getBaseName();
    }
    // fully-qualify the method
    goldenMethodName = classData.getName() + "." + goldenMethodName;
    // replace nested class separator $ by .
    goldenMethodName = goldenMethodName.replaceAll(Pattern.quote("$"), ".");

    TraceSignatureVisitor v = new TraceSignatureVisitor(Opcodes.ACC_PUBLIC);
    SignatureReader r = new SignatureReader(methodDescriptor);
    r.accept(v);

    // for the scope of this method, signature = signature of the method excluding the method name
    String goldenSignature = v.getDeclaration();
    // get parameter type list string which is enclosed by round brackets ()
    goldenSignature = goldenSignature.substring(1, goldenSignature.length() - 1);

    // collect all the signatures with the same method name as golden method
    Map<String, Integer> candidateSignatureToCcn = new HashMap<String, Integer>();
    for (FunctionMetric singleMethodMetrics : methodMetrics) {
        String candidateMethodName = singleMethodMetrics.name.substring(0,
                singleMethodMetrics.name.indexOf('('));
        String candidateSignature = stripTypeParameters(singleMethodMetrics.name
                .substring(singleMethodMetrics.name.indexOf('(') + 1, singleMethodMetrics.name.length() - 1));
        if (goldenMethodName.equals(candidateMethodName)) {
            candidateSignatureToCcn.put(candidateSignature, singleMethodMetrics.ccn);
        }
    }

    // if only one signature, no signature matching needed
    if (candidateSignatureToCcn.size() == 1) {
        return candidateSignatureToCcn.values().iterator().next();
    }

    // else, do signature matching and find the best match

    // update golden signature using reflection
    if (!goldenSignature.isEmpty()) {
        try {
            String[] goldenParameterTypeStrings = goldenSignature.split(",");
            Class<?>[] goldenParameterTypes = new Class[goldenParameterTypeStrings.length];
            for (int i = 0; i < goldenParameterTypeStrings.length; i++) {
                goldenParameterTypes[i] = ClassUtils.getClass(goldenParameterTypeStrings[i].trim(), false);
            }
            Class<?> klass = ClassUtils.getClass(classData.getName(), false);
            if (isConstructor) {
                Constructor<?> realMethod = klass.getDeclaredConstructor(goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            } else {
                Method realMethod = klass.getDeclaredMethod(methodName, goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            }
            // replace varargs ellipsis with array notation
            goldenSignature = goldenSignature.replaceAll("\\.\\.\\.", "[]");
            // extract the parameter type list string
            goldenSignature = goldenSignature.substring(goldenSignature.indexOf("(") + 1,
                    goldenSignature.length() - 1);
            // strip the type parameters to get raw types
            goldenSignature = stripTypeParameters(goldenSignature);
        } catch (Exception e) {
            logger.error("Error while getting method CC for " + goldenMethodName, e);
            return 0;
        }
    }
    // replace nested class separator $ by .
    goldenSignature = goldenSignature.replaceAll(Pattern.quote("$"), ".");

    // signature matching - due to loss of fully qualified parameter types from JavaCC, get ccn for the closest match
    double signatureMatchPercentTillNow = 0;
    for (Entry<String, Integer> candidateSignatureToCcnEntry : candidateSignatureToCcn.entrySet()) {
        String candidateSignature = candidateSignatureToCcnEntry.getKey();
        double currentMatchPercent = matchSignatures(candidateSignature, goldenSignature);
        if (currentMatchPercent == 1) {
            return candidateSignatureToCcnEntry.getValue();
        }
        if (currentMatchPercent > signatureMatchPercentTillNow) {
            complexity = candidateSignatureToCcnEntry.getValue();
            signatureMatchPercentTillNow = currentMatchPercent;
        }
    }

    return complexity;
}