Example usage for java.lang Class getConstructors

List of usage examples for java.lang Class getConstructors

Introduction

In this page you can find the example usage for java.lang Class getConstructors.

Prototype

@CallerSensitive
public Constructor<?>[] getConstructors() throws SecurityException 

Source Link

Document

Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.

Usage

From source file:org.eclipse.wb.internal.core.model.property.table.HtmlTooltipHelper.java

/**
 * @return the length of text in given HTML. Uses internal class, so may fail, in this case
 *         returns length on HTML./*from  w w w . j  ava  2s . c  o m*/
 */
private static int getTextLength(String html) {
    StringReader htmlStringReader = new StringReader(html);
    try {
        ClassLoader classLoader = PropertyTable.class.getClassLoader();
        Class<?> readerClass = classLoader.loadClass("org.eclipse.jface.internal.text.html.HTML2TextReader");
        Object reader = readerClass.getConstructors()[0].newInstance(htmlStringReader, null);
        String text = (String) ReflectionUtils.invokeMethod(reader, "getString()");
        return text.length();
    } catch (Throwable e) {
        return html.length();
    }
}

From source file:org.force66.beantester.utils.InstantiationUtils.java

public static Constructor<?> findPublicConstructor(Class<?> klass) {
    Validate.notNull(klass, "Null class not allowed.");
    Constructor<?> nullConstructor = ConstructorUtils.getAccessibleConstructor(klass, new Class<?>[0]);
    if (nullConstructor != null) {
        return nullConstructor;
    }//ww  w .j av  a  2 s  .  co m

    Constructor<?>[] constructorArray = klass.getConstructors();
    for (Constructor<?> constructor : constructorArray) {
        if (Modifier.isPublic(constructor.getModifiers())) {
            return constructor;
        }
    }

    return null;
}

From source file:org.xulux.utils.ClassLoaderUtils.java

/**
 * Instantiates the parent object of an inner class.
 * @param clazz the class/*  w w  w .j  a  va2 s.  c o  m*/
 * @return the instance of the inner class
 */
protected static Object getParentObjectForInnerClass(Class clazz) {
    String name = clazz.getName();
    int index = name.indexOf("$");
    if (index != -1) {
        name = name.substring(0, index);
        // cannot think of a scenario when this is null,
        Class clz = getClass(name.substring(0, index));
        ArrayList parms = new ArrayList();
        boolean hasEmptyConstructor = false;
        Constructor[] css = clz.getConstructors();
        for (int i = 0; i < css.length; i++) {
            Constructor cs = css[i];
            if (cs.getParameterTypes().length == 0) {
                hasEmptyConstructor = true;
                parms = new ArrayList();
                break;
            } else {
                for (int j = 0; j < cs.getParameterTypes().length; j++) {
                    Class c = cs.getParameterTypes()[j];
                    Object object = null;
                    try {
                        object = c.newInstance();
                    } catch (Exception e) {
                        // eat it..
                    } finally {
                        parms.add(object);
                    }
                }
            }
        }
        return getObjectFromClass(getClass(name.substring(0, index)), parms);
    }
    return null;
}

From source file:com.pentaho.big.data.bundles.impl.shim.common.ShimBridgingClassloader.java

public static Object create(BundleContext bundleContext, String className, List<Object> arguments)
        throws KettlePluginException, ClassNotFoundException, IllegalAccessException, InstantiationException,
        InvocationTargetException {
    ShimBridgingClassloader shimBridgingClassloader = new ShimBridgingClassloader(pluginClassloaderGetter
            .getPluginClassloader(LifecyclePluginType.class.getCanonicalName(), HADOOP_SPOON_PLUGIN),
            bundleContext);/*from  w w w . ja  v  a 2 s  .c  o  m*/
    Class<?> clazz = Class.forName(className, true, shimBridgingClassloader);
    if (arguments == null || arguments.size() == 0) {
        return clazz.newInstance();
    }
    for (Constructor<?> constructor : clazz.getConstructors()) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == arguments.size()) {
            boolean match = true;
            for (int i = 0; i < parameterTypes.length; i++) {
                Object o = arguments.get(i);
                if (o != null && !parameterTypes[i].isInstance(o)) {
                    match = false;
                    break;
                }
            }
            if (match) {
                return constructor.newInstance(arguments.toArray());
            }
        }
    }
    throw new InstantiationException(
            "Unable to find constructor for class " + className + " with arguments " + arguments);
}

From source file:net.servicefixture.util.ReflectionUtils.java

/**
 * Returns true if it is an enumeration type.
 * /*w ww  . jav a 2s .c  o m*/
 * @param type
 * @return
 */
public static boolean isEnumarationPatternClass(Class type) {
    try {
        //JDK1.4 Enumeration Pattern
        Constructor[] constructors = type.getConstructors();
        for (int i = 0; i < constructors.length; i++) {
            if (Modifier.isPublic(constructors[i].getModifiers())) {
                return false;
            }
        }
        type.getMethod("fromString", new Class[] { String.class });
        return true;
    } catch (SecurityException e) {
    } catch (NoSuchMethodException e) {
    }
    return false;
}

From source file:io.neba.core.resourcemodels.factory.ModelInstantiator.java

/**
 * @return either the default or an @Inject constructor, if present. Fails if neither a public default constructor nor a public @Inject constructor is
 * present, of if multiple @Inject constructors exist.
 *//*from   w  w  w.  j ava 2  s. c o m*/
@SuppressWarnings("unchecked")
@Nonnull
private static <T> ModelConstructor<T> resolveConstructor(@Nonnull Class<T> modelType) {
    ModelConstructor<T> constructor;
    Constructor<T> injectionConstructor = null, defaultConstructor = null;
    for (Constructor c : modelType.getConstructors()) {
        if (c.getParameterCount() == 0) {
            defaultConstructor = c;
        }

        if (!annotations(c).containsName(INJECT_ANNOTATION_NAME)) {
            continue;
        }

        if (injectionConstructor != null) {
            throw new InvalidModelException("Unable to instantiate model " + modelType + ". "
                    + "Found more than one constructor annotated with @Inject: " + injectionConstructor + ", "
                    + c);
        }

        injectionConstructor = c;
    }

    if (injectionConstructor != null) {
        Type[] parameters = injectionConstructor.getGenericParameterTypes();
        ServiceDependency[] serviceDependencies = new ServiceDependency[parameters.length];
        Annotation[][] parameterAnnotations = injectionConstructor.getParameterAnnotations();
        for (int i = 0; i < parameters.length; ++i) {
            Filter filter = findFilterAnnotation(parameterAnnotations[i]);
            serviceDependencies[i] = new ServiceDependency(parameters[i], modelType, filter);
        }
        constructor = new ModelConstructor<>(injectionConstructor, serviceDependencies);
    } else if (defaultConstructor != null) {
        constructor = new ModelConstructor<>(defaultConstructor);
    } else {
        throw new InvalidModelException("The model " + modelType
                + " has neither a public default constructor nor a public constructor annotated with @Inject.");
    }

    return constructor;
}

From source file:run.ace.Utils.java

public static Object invokeConstructorWithBestParameterMatch(Class c, Object[] args) {
    Constructor[] constructors = c.getConstructors();
    int numArgs = args.length;
    // Look at all constructors
    for (Constructor constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        // Does it have the right number of parameters?
        if (parameterTypes.length == numArgs) {
            // Are all the parameters types that will work?
            Object[] matchingArgs = tryToMakeArgsMatch(args, parameterTypes, false);
            if (matchingArgs != null) {
                try {
                    return constructor.newInstance(matchingArgs);
                } catch (InstantiationException ex) {
                    throw new RuntimeException(
                            "Error instantiating " + c.getSimpleName() + ": " + ex.toString());
                } catch (IllegalAccessException ex) {
                    throw new RuntimeException(c.getSimpleName() + "'s matching constructor is inaccessible");
                } catch (InvocationTargetException ex) {
                    throw new RuntimeException("Error in " + c.getSimpleName() + "'s constructor: "
                            + ex.getTargetException().toString());
                }//w ww.j  av a2  s . co m
            }
        }
    }
    throw new RuntimeException(
            c + " does not have a public constructor with " + numArgs + " matching parameter type(s).");
}

From source file:org.apache.axis2.jaxws.marshaller.impl.alt.LegacyExceptionUtil.java

/**
 * Find a construcor that matches this set of properties
 *
 * @param cls//from  w w  w  .  jav a 2  s.com
 * @param pdList
 * @param childNames returned in the order that they occur in the constructor
 * @return Constructor or null
 */
private static Constructor findConstructor(Class cls, List<PropertyDescriptorPlus> pdList,
        List<String> childNames) {
    Constructor[] constructors = cls.getConstructors();
    Constructor constructor = null;
    if (constructors != null) {
        for (int i = 0; i < constructors.length && constructor == null; i++) {
            Constructor tryConstructor = constructors[i];
            if (tryConstructor.getParameterTypes().length == pdList.size()) {
                // Try and find the best match using the property types
                List<PropertyDescriptorPlus> list = new ArrayList<PropertyDescriptorPlus>(pdList);
                List<PropertyDescriptorPlus> args = new ArrayList<PropertyDescriptorPlus>();

                Class[] parms = tryConstructor.getParameterTypes();
                boolean valid = true;

                // Assume the message is first in the constructor
                for (int j = 0; j < list.size(); j++) {
                    if ("message".equals(list.get(j).getPropertyName())) {
                        args.add(list.remove(j));
                    }
                }
                if (args.size() != 1 || !parms[0].isAssignableFrom(args.get(0).getPropertyType())) {
                    valid = false;
                }

                // Now process the rest of the args
                for (int j = 1; j < parms.length && valid; j++) {
                    // Find a compatible argument
                    Class parm = parms[j];
                    boolean found = false;
                    for (int k = 0; k < list.size() && !found; k++) {
                        Class arg = list.get(k).getPropertyType();
                        if (parm.isAssignableFrom(arg)) {
                            found = true;
                            args.add(list.remove(k));
                        }
                    }
                    // If no compatible argument then this constructor is not valid
                    if (!found) {
                        valid = false;
                    }
                }
                // A constructor is found
                if (valid) {
                    constructor = tryConstructor;
                    for (int index = 0; index < args.size(); index++) {
                        childNames.add(args.get(index).getPropertyName());
                    }
                }
            }
        }
    }

    return constructor;
}

From source file:org.eclipse.winery.repository.resources.AbstractComponentsResource.java

/**
 * @return an instance of the requested resource
 * @throws NotFoundException if resource doesn't exist.
 *///from w  w w.j  a va  2  s .  c o m
public static AbstractComponentInstanceResource getComponentInstaceResource(TOSCAComponentId tcId) {
    String type = Util.getTypeForComponentId(tcId.getClass());
    if (!Repository.INSTANCE.exists(tcId)) {
        AbstractComponentsResource.logger.debug("TOSCA component id " + tcId.toString() + " not found");
        throw new NotFoundException("TOSCA component id " + tcId.toString() + " not found");
    }
    Class<? extends AbstractComponentInstanceResource> newResource = AbstractComponentsResource
            .getComponentInstanceResourceClassForType(type);
    Constructor<?>[] constructors = newResource.getConstructors();
    assert (constructors.length == 1);
    AbstractComponentInstanceResource newInstance;
    try {
        newInstance = (AbstractComponentInstanceResource) constructors[0].newInstance(tcId);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        AbstractComponentsResource.logger.error("Could not instantiate sub resource " + tcId);
        throw new IllegalStateException("Could not instantiate sub resource", e);
    }
    return newInstance;
}

From source file:org.wso2.carbon.governance.metadata.Util.java

private static Map<String, BaseProvider> getBaseProviderMap() throws MetadataException {
    if (baseProviderMap != null) {
        return baseProviderMap;
    }/* w ww  . ja  v a 2s.c om*/

    ConcurrentHashMap<String, BaseProvider> providerMap = new ConcurrentHashMap<String, BaseProvider>();
    try {
        FileInputStream fileInputStream = new FileInputStream(getConfigFile());
        StAXOMBuilder builder = new StAXOMBuilder(fileInputStream);
        OMElement configElement = builder.getDocumentElement();
        OMElement metadataProviders = configElement.getFirstChildWithName(new QName("metadataProviders"))
                .getFirstChildWithName(new QName("baseProviders"));
        Iterator<OMElement> itr = metadataProviders.getChildrenWithLocalName("provider");
        while (itr.hasNext()) {
            OMElement metadataProvider = itr.next();
            String providerClass = metadataProvider.getAttributeValue(new QName("class")).trim();
            String mediaType = metadataProvider.getAttributeValue(new QName(Constants.ATTRIBUTE_MEDIA_TYPE));
            String versionMediaType = metadataProvider
                    .getAttributeValue(new QName(Constants.ATTRIBUTE_VERSION_MEDIA_TYPE));

            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Class<BaseProvider> classObj = (Class<BaseProvider>) Class.forName(providerClass, true, loader);

            if (!providerMap.containsKey(mediaType)) {
                providerMap.put(mediaType,
                        (BaseProvider) classObj.getConstructors()[0].newInstance(mediaType, versionMediaType));
            } else {
                //                    log.error("Classification URI already exists")
            }
        }
    } catch (Exception e) {
        throw new MetadataException(e.getMessage(), e);
    }

    return Util.baseProviderMap = providerMap;
}