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:com.brienwheeler.svc.attrs.impl.PersistentAttributeServiceBase.java

@SuppressWarnings("unchecked")
private AttrClass createAttribute(OwnerClass owner, String name, String value) {
    Class<AttrClass> clazz = persistentAttributeDao.getEntityClass();
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        if (parameterTypes.length == 3 && parameterTypes[0].equals(owner.getClass())
                && parameterTypes[1].equals(String.class) && parameterTypes[2].equals(String.class)) {
            try {
                return (AttrClass) constructor.newInstance(owner, name, value);
            } catch (Exception e) {
                throw new ReflectionException("error instantiating object of type " + clazz.getSimpleName(), e);
            }/*from  w  w  w.j av a 2  s .  c o  m*/
        }
    }

    throw new ReflectionException(clazz.getSimpleName() + " does not have " + clazz.getSimpleName() + "("
            + owner.getClass().getSimpleName() + ",String,String) constructor");
}

From source file:com.metadave.stow.TestStow.java

@Test
public void testGen() throws Exception {
    InputStream is = this.getClass().getResourceAsStream("/Stow.stg");
    File f = File.createTempFile("stow", "test.stg");
    String root = f.getParent();/*  w ww.  j  av  a 2  s  .c  o  m*/
    String classdir = root + File.separator + "stowtest";

    String stgPath = f.getAbsolutePath();
    String stowStg = org.apache.commons.io.IOUtils.toString(is);

    org.apache.commons.io.FileUtils.writeStringToFile(f, stowStg);

    File d = new File(classdir);
    d.mkdirs();

    Stow.generateObjects(stgPath, "stowtest", "Test", classdir);

    File testSTBean = new File(classdir + File.separator + "TestSTBean.java");
    assertTrue(testSTBean.exists());

    File testSTAccessor = new File(classdir + File.separator + "TestSTAccessor.java");
    assertTrue(testSTAccessor.exists());

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, testSTBean.getAbsolutePath());
    compiler.run(null, null, null, testSTAccessor.getAbsolutePath());

    File testSTAccessorClass = new File(classdir + File.separator + "TestSTAccessor.class");
    assertTrue(testSTAccessorClass.exists());

    File testSTBeanClass = new File(classdir + File.separator + "TestSTBean.class");
    assertTrue(testSTBeanClass.exists());

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File(root).toURI().toURL() });
    Class<?> cls = Class.forName("stowtest.TestSTBean", true, classLoader);

    Constructor<?> c = cls.getConstructors()[0];
    STGroup stg = new STGroupFile(f.getAbsolutePath());
    Object o = c.newInstance(stg);

    Set<String> methods = new HashSet<String>();
    methods.add("addPackage");
    methods.add("addBeanClass");
    methods.add("addTemplateName");
    methods.add("addAccessor");

    int count = 0;
    for (Method m : o.getClass().getMethods()) {
        if (methods.contains(m.getName())) {
            count++;
        }
    }
    assertEquals("Look for 8 generated methods", 8, count);
}

From source file:ch.digitalfondue.npjt.ConstructorAnnotationRowMapper.java

@SuppressWarnings("unchecked")
public ConstructorAnnotationRowMapper(Class<T> clazz, Collection<ColumnMapperFactory> columnMapperFactories) {
    int constructorCount = clazz.getConstructors().length;
    Assert.isTrue(constructorCount == 1, "The class " + clazz.getName()
            + " must have exactly one public constructor, " + constructorCount + " are present");

    con = (Constructor<T>) clazz.getConstructors()[0];
    mappedColumn = from(clazz, con.getParameterAnnotations(), con.getParameterTypes(), columnMapperFactories);
}

From source file:de.escalon.hypermedia.spring.uber.UberUtils.java

/**
 * Renders input fields for bean properties of bean to add or update or patch.
 *
 * @param uberFields//from  w  w w  .  j ava  2 s  .co m
 *         to add to
 * @param beanType
 *         to render
 * @param annotatedParameters
 *         which describes the method
 * @param annotatedParameter
 *         which requires the bean
 * @param currentCallValue
 *         sample call value
 */
private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType,
        ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue,
        String parentParamName, Set<String> knownFields) {
    // TODO collection, map and object node creation are only describable by an annotation, not via type reflection
    if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType)
            || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) {
        return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder?
    }
    try {
        Constructor[] constructors = beanType.getConstructors();
        // find default ctor
        Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
        // find ctor with JsonCreator ann
        if (constructor == null) {
            constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
        }
        Assert.notNull(constructor,
                "no default constructor or JsonCreator found for type " + beanType.getName());
        int parameterCount = constructor.getParameterTypes().length;

        if (parameterCount > 0) {
            Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations();

            Class[] parameters = constructor.getParameterTypes();
            int paramIndex = 0;
            for (Annotation[] annotationsOnParameter : annotationsOnParameters) {
                for (Annotation annotation : annotationsOnParameter) {
                    if (JsonProperty.class == annotation.annotationType()) {
                        JsonProperty jsonProperty = (JsonProperty) annotation;

                        // TODO use required attribute of JsonProperty for required fields
                        String paramName = jsonProperty.value();
                        Class parameterType = parameters[paramIndex];
                        Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue,
                                paramName);
                        MethodParameter methodParameter = new MethodParameter(constructor, paramIndex);

                        addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                                annotatedParameters, parentParamName, paramName, parameterType, propertyValue,
                                knownFields);
                        paramIndex++; // increase for each @JsonProperty
                    }
                }
            }
            Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator "
                    + constructor.getName() + " are annotated with @JsonProperty");
        }

        Set<String> knownConstructorFields = new HashSet<String>(uberFields.size());
        for (UberField sirenField : uberFields) {
            knownConstructorFields.add(sirenField.getName());
        }

        // TODO support Option provider by other method args?
        Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);

        // add input field for every setter
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) {
            final Method writeMethod = propertyDescriptor.getWriteMethod();
            String propertyName = propertyDescriptor.getName();

            if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) {
                continue;
            }
            final Class<?> propertyType = propertyDescriptor.getPropertyType();

            Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName);
            MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0);

            addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter,
                    annotatedParameters, parentParamName, propertyName, propertyType, propertyValue,
                    knownConstructorFields);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to write input fields for constructor", e);
    }
}

From source file:org.tangram.guice.DefaultTangramContextListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    LOG.info("contextInitialized()");
    ServletContext context = servletContextEvent.getServletContext();
    String webModuleClassName = context.getInitParameter(SHIRO_WEB_MODULE_CLASS);
    String dispatcherPath = context.getInitParameter(DISPATCHER_PATH);
    dispatcherPath = dispatcherPath == null ? "/s" : dispatcherPath;
    if (StringUtils.isNotBlank(webModuleClassName)) {
        try {//ww  w  .ja  v  a  2s. com
            Class<?> forName = Class.forName(webModuleClassName);
            Object[] args = { context, dispatcherPath };
            shiroWebModule = (Module) forName.getConstructors()[0].newInstance(args);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain shiro web module", e);
        } // try/catch
    } // if
    LOG.info("contextInitialized() shiro web module: {} :{}", shiroWebModule, webModuleClassName);

    String servletModuleClassName = context.getInitParameter(SERVLET_MODULE_CLASS);
    if (StringUtils.isNotBlank(servletModuleClassName)) {
        try {
            Class<?> forName = Class.forName(servletModuleClassName);
            servletModule = (ServletModule) forName.getConstructors()[0].newInstance(new Object[0]);
        } catch (Exception e) {
            LOG.error("contextInitialized() cannot obtain servlet module", e);
        } // try/catch
    } // if
    servletModule = servletModule == null ? new TangramServletModule() : servletModule;
    LOG.info("contextInitialized() servlet module: {} :{}", servletModule, servletModuleClassName);

    super.contextInitialized(servletContextEvent);
}

From source file:org.eclipse.wb.internal.core.gef.policy.layout.generic.SelectionEditPolicyInstaller.java

/**
 * Attempts to create {@link SelectionEditPolicy} instance using different constructor variants,
 * may return <code>null</code>.
 */// www. j  a  va 2  s. co  m
private SelectionEditPolicy createPolicy(Class<?> selectionPolicyClass) {
    Constructor<?> constructor = selectionPolicyClass.getConstructors()[0];
    // container model + child model
    try {
        return (SelectionEditPolicy) constructor.newInstance(container, child);
    } catch (Throwable e) {
    }
    // only child model
    try {
        return (SelectionEditPolicy) constructor.newInstance(child);
    } catch (Throwable e) {
    }
    // only container model
    try {
        return (SelectionEditPolicy) constructor.newInstance(container);
    } catch (Throwable e) {
    }
    // no arguments
    try {
        return (SelectionEditPolicy) constructor.newInstance();
    } catch (Throwable e) {
    }
    // fail
    return null;
}

From source file:io.lavagna.common.ConstructorAnnotationRowMapper.java

@SuppressWarnings("unchecked")
public ConstructorAnnotationRowMapper(Class<T> clazz) {
    int constructorCount = clazz.getConstructors().length;
    Assert.isTrue(constructorCount == 1, "The class " + clazz.getName()
            + " must have exactly one public constructor, " + constructorCount + " are present");

    con = (Constructor<T>) clazz.getConstructors()[0];
    mappedColumn = from(clazz, con.getParameterAnnotations(), con.getParameterTypes());
}

From source file:org.openvpms.web.component.im.edit.IMObjectEditorFactory.java

/**
 * Returns a constructor to construct a new editor.
 *
 * @param type    the editor type/* w  w  w  . j ava 2s  .  c  o m*/
 * @param object  the object to edit
 * @param parent  the parent object. May be {@code null}
 * @param context the layout context. May be {@code null}
 * @return a constructor to construct the editor, or {@code null} if none can be found
 */
private Constructor getConstructor(Class type, IMObject object, IMObject parent, LayoutContext context) {
    Constructor[] ctors = type.getConstructors();

    for (Constructor ctor : ctors) {
        // check parameters
        Class<?>[] ctorTypes = ctor.getParameterTypes();
        if (ctorTypes.length == 3) {
            Class<?> ctorObj = ctorTypes[0];
            Class<?> ctorParent = ctorTypes[1];
            Class<?> ctorLayout = ctorTypes[2];

            if (ctorObj.isAssignableFrom(object.getClass())
                    && ((parent != null && ctorParent.isAssignableFrom(parent.getClass()))
                            || (parent == null && IMObject.class.isAssignableFrom(ctorParent)))
                    && ((context != null && ctorLayout.isAssignableFrom(context.getClass()))
                            || (context == null && LayoutContext.class.isAssignableFrom(ctorLayout)))) {
                return ctor;
            }
        }
    }
    return null;
}

From source file:org.xmlsh.util.JavaUtils.java

public static <T> T newObject(Class<T> cls, Object... args) throws InvalidArgumentException,
        InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    @SuppressWarnings("unchecked")
    Constructor<T>[] constructors = (Constructor<T>[]) cls.getConstructors();
    Constructor<T> c = getBestConstructor(constructors, args);
    if (c == null)
        throw new InvalidArgumentException("Cannot find constructor for: " + cls.getName());
    return c.newInstance(args);
}

From source file:org.xchain.framework.jxpath.MethodLookupUtils.java

/**
 * Look up a constructor.// w w w  .ja  va  2 s  .co  m
 * @param targetClass the class constructed
 * @param parameters arguments
 * @return Constructor found if any.
 */
public static Constructor lookupConstructor(Class targetClass, Object[] parameters) {
    boolean tryExact = true;
    int count = parameters == null ? 0 : parameters.length;
    Class[] types = new Class[count];
    for (int i = 0; i < count; i++) {
        Object param = parameters[i];
        if (param != null) {
            types[i] = param.getClass();
        } else {
            types[i] = null;
            tryExact = false;
        }
    }

    Constructor constructor = null;

    if (tryExact) {
        // First - without type conversion
        try {
            constructor = targetClass.getConstructor(types);
            if (constructor != null) {
                return constructor;
            }
        } catch (NoSuchMethodException ex) { //NOPMD
            // Ignore
        }
    }

    int currentMatch = 0;
    boolean ambiguous = false;

    // Then - with type conversion
    Constructor[] constructors = targetClass.getConstructors();
    for (int i = 0; i < constructors.length; i++) {
        int match = matchParameterTypes(constructors[i].getParameterTypes(), parameters);
        if (match != NO_MATCH) {
            if (match > currentMatch) {
                constructor = constructors[i];
                currentMatch = match;
                ambiguous = false;
            } else if (match == currentMatch) {
                ambiguous = true;
            }
        }
    }
    if (ambiguous) {
        throw new JXPathException("Ambigous constructor " + Arrays.asList(parameters));
    }
    return constructor;
}