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:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Create a bean element for the given class.
 *
 * @param clazz the target class/*from   w  w  w. j av a 2  s  .  c  o m*/
 * @return the bean element or a list of beans for each service provider
 * available
 */
public List<?> createElement(Class<?> clazz) {
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) {
        return createServiceProviderElements(clazz);
    }
    if (clazz.getConstructors().length == 0) {
        log.warn("Class {} has no public no-argument constructor!", clazz);
        return Collections.emptyList();
    }
    Object obj;
    try {
        obj = clazz.newInstance();
        //build a "bean" element for each class
        buildBeanElement(obj);
        return Arrays.asList(obj);
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
    return Collections.emptyList();
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

private Constructor<?> findCustomConstructor(Class<?> typeClass) {
    Class<?> superClass = typeClass.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)) {
        Constructor<?> customSuperConstructor = findCustomConstructor(typeClass.getSuperclass());
        if (customSuperConstructor != null) {
            return customSuperConstructor;
        }//from   w w w  .j a va2 s  .  c om
    }
    Constructor<?>[] constructors = typeClass.getConstructors();
    if (constructors.length == 0
            || (constructors.length == 1 && constructors[0].getParameterTypes().length == 0)) {
        return null;
    } else {
        for (Constructor<?> constructor : constructors) {
            if (constructor.getParameterTypes().length > 0) {
                return constructor;
            }
        }
        //this should never happen
        throw new RuntimeException(String.format(
                "Expected a constructor taking at least one argument in %s but no such constructors were found",
                typeClass.getName()));
    }
}

From source file:org.apache.carbondata.hadoop.api.CarbonInputFormat.java

public CarbonReadSupport<T> getReadSupportClass(Configuration configuration) {
    String readSupportClass = configuration.get(CARBON_READ_SUPPORT);
    //By default it uses dictionary decoder read class
    CarbonReadSupport<T> readSupport = null;
    if (readSupportClass != null) {
        try {/* w w  w .  j  av  a2  s. c o m*/
            Class<?> myClass = Class.forName(readSupportClass);
            Constructor<?> constructor = myClass.getConstructors()[0];
            Object object = constructor.newInstance();
            if (object instanceof CarbonReadSupport) {
                readSupport = (CarbonReadSupport) object;
            }
        } catch (ClassNotFoundException ex) {
            LOG.error("Class " + readSupportClass + "not found", ex);
        } catch (Exception ex) {
            LOG.error("Error while creating " + readSupportClass, ex);
        }
    } else {
        readSupport = new DictionaryDecodeReadSupport<>();
    }
    return readSupport;
}

From source file:org.opoo.press.impl.FactoryImpl.java

@Override
public Renderer createRenderer(Site site) {
    //return new RendererImpl(site, getTemplateLoaders());

    String className = (String) site.getTheme().get("renderer");
    if (className != null) {
        Class<Renderer> clazz;
        try {/*from ww w .  java 2s . c  o m*/
            clazz = ClassUtils.getClass(site.getClassLoader(), className);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }

        Constructor<?>[] constructors = clazz.getConstructors();
        Constructor<?> theConstructor = null;
        for (Constructor<?> constructor : constructors) {
            Class<?>[] types = constructor.getParameterTypes();
            if (types.length == 1 && types[0].equals(Site.class)) {
                theConstructor = constructor;
                break;
            }
        }

        try {
            if (theConstructor != null) {
                return (Renderer) theConstructor.newInstance(site);
            } else {
                Renderer renderer = clazz.newInstance();
                if (renderer instanceof SiteAware) {
                    ((SiteAware) renderer).setSite(site);
                }
                if (renderer instanceof ConfigAware) {
                    ((ConfigAware) renderer).setConfig(site.getConfig());
                }
                return renderer;
            }

        } catch (InstantiationException e) {
            throw new RuntimeException("error instance: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException("error instance: " + e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("error instance: " + e.getTargetException(), e.getTargetException());
        }
    }

    //default: freemarker
    return new FreeMarkerRenderer(site);
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public List<Constructor> findAnnotatedConstructors(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();/*  w  w  w .j a v  a2 s  .  co  m*/
    List<ClassInfo> seen = new ArrayList<ClassInfo>();
    List<Constructor> constructors = new ArrayList<Constructor>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && "<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Constructor constructor : clazz.getConstructors()) {
                    if (constructor.isAnnotationPresent(annotation)) {
                        constructors.add(constructor);
                    }
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return constructors;
}

From source file:com.konakart.server.KKGWTServiceImpl.java

/**
 * Create a new KKAppEng engine from a class of the specified name. We look at the constructors
 * in the specified class to find out if there are any constructors declared that will accept an
 * EngineConfig object. If there are, we use that constructor with the specified EngineConfig
 * object. If not, we use the default constructor.
 * //from ww w.  ja  va2  s .  c o  m
 * @param kkEngineName
 *            the name of the class that implements KKAppEng
 * @param engConfig
 *            the engine configuration object
 * @return a newly-instantiated KKAppEng
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 */
private KKAppEng getAppEngByName(String kkEngineName, EngineConfigIf engConfig) throws InstantiationException,
        IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException {
    System.out.println("getAppEngByName(" + kkEngineName + ")");
    Class<?> engineClass = Class.forName(kkEngineName);
    KKAppEng kkAppEng = null;
    Constructor<?>[] constructors = engineClass.getConstructors();
    Constructor<?> engConstructor = null;
    if (constructors != null && constructors.length > 0) {
        for (int i = 0; i < constructors.length; i++) {
            Constructor<?> constructor = constructors[i];
            Class<?>[] parmTypes = constructor.getParameterTypes();
            if (parmTypes != null && parmTypes.length == 1) {
                String parmName = parmTypes[0].getName();
                if (parmName != null && parmName.equals("com.konakart.appif.EngineConfigIf")) {
                    engConstructor = constructor;
                }
            }
        }
    }

    if (engConstructor != null) {
        kkAppEng = (KKAppEng) engConstructor.newInstance(engConfig);
        if (true) {
            if (log.isInfoEnabled()) {
                log.info("Created " + kkEngineName + " using EngineConfigIf constructor for store '"
                        + engConfig.getStoreId() + "'");
            }
        }
    } else {
        kkAppEng = (KKAppEng) engineClass.newInstance();
        if (true) {
            if (log.isInfoEnabled()) {
                log.info("Created " + kkEngineName + " using default constructor for store '"
                        + engConfig.getStoreId() + "'");
            }
        }
    }

    return kkAppEng;
}

From source file:de.fuberlin.wiwiss.r2r.Repository.java

private FunctionManager loadFunctionManager(Source source) {
    String fm = Config.getProperty("r2r.FunctionManager", "de.fuberlin.wiwiss.r2r.BasicFunctionManager");
    String error = null;/*from  ww w. j  a va2 s  .  c o  m*/
    Exception exception;
    try {
        Class<?> fmclass = Class.forName(fm);
        boolean constructorWithSource = false;
        Constructor<?> c = null;
        for (Constructor<?> constructor : fmclass.getConstructors()) {
            Class<?>[] pTypes = constructor.getParameterTypes();
            if (c == null && pTypes.length == 0)
                c = constructor;
            if (pTypes.length == 1 && pTypes[0] == Source.class) {
                c = constructor;
                constructorWithSource = true;
            }
        }

        if (constructorWithSource)
            return (FunctionManager) c.newInstance(source);
        else
            return (FunctionManager) c.newInstance();
    } catch (InstantiationException e) {
        exception = e;
    } catch (IllegalAccessException e) {
        exception = e;
    } catch (ClassNotFoundException e) {
        exception = e;
    } catch (IllegalArgumentException e) {
        exception = e;
    } catch (InvocationTargetException e) {
        exception = e;
    }
    error = "Could not load Function Manager: " + fm + ". Cause: " + exception;
    if (log.isDebugEnabled())
        log.debug(error);
    if (Config.rethrowActivated())
        throw new R2RException(error, exception);

    return null;
}

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * ???(xiaojf?)//from   www .  java 2 s.  c  om
 */
@Override
protected void bind(final HttpServletRequest request, final Object command) {
    final PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(command.getClass());
    for (final PropertyDescriptor pd : pds) {
        final Class<?> clas = pd.getPropertyType();// ?class
        final boolean isSimpleProperty = BeanUtils.isSimpleProperty(clas);
        final boolean isInterface = clas.isInterface();
        final boolean hasConstruct = clas.getConstructors().length == 0 ? false : true;
        if (!isSimpleProperty && !isInterface && hasConstruct) {
            // 
            try {
                pd.getWriteMethod().invoke(command, clas.newInstance());
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        super.bind(request, command);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.github.hateoas.forms.spring.xhtml.XhtmlResourceMessageConverter.java

Object recursivelyCreateObject(Class<?> clazz, MultiValueMap<String, String> formValues,
        String parentParamName) {

    if (Map.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Map not supported");
    } else if (Collection.class.isAssignableFrom(clazz)) {
        throw new IllegalArgumentException("Collection not supported");
    } else {//from   ww  w.  ja va2s .  c  o m
        try {
            Constructor[] constructors = clazz.getConstructors();
            Constructor constructor = PropertyUtils.findDefaultCtor(constructors);
            if (constructor == null) {
                constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class);
            }
            Assert.notNull(constructor, "no default constructor or JsonCreator found");
            int parameterCount = constructor.getParameterTypes().length;
            Object[] args = new Object[parameterCount];
            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;
                            String paramName = jsonProperty.value();
                            List<String> formValue = formValues.get(parentParamName + paramName);
                            Class<?> parameterType = parameters[paramIndex];
                            if (DataType.isSingleValueType(parameterType)) {
                                if (formValue != null) {
                                    if (formValue.size() == 1) {
                                        args[paramIndex++] = DataType.asType(parameterType, formValue.get(0));
                                    } else {
                                        //                                        // TODO create proper collection type
                                        throw new IllegalArgumentException("variable list not supported");
                                        //                                        List<Object> listValue = new ArrayList<Object>();
                                        //                                        for (String item : formValue) {
                                        //                                            listValue.add(DataType.asType(parameterType, formValue.get(0)));
                                        //                                        }
                                        //                                        args[paramIndex++] = listValue;
                                    }
                                } else {
                                    args[paramIndex++] = null;
                                }
                            } else {
                                args[paramIndex++] = recursivelyCreateObject(parameterType, formValues,
                                        parentParamName + paramName + ".");
                            }
                        }
                    }
                }
                Assert.isTrue(args.length == paramIndex,
                        "not all constructor arguments of @JsonCreator are " + "annotated with @JsonProperty");
            }
            Object ret = constructor.newInstance(args);
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                Method writeMethod = propertyDescriptor.getWriteMethod();
                String name = propertyDescriptor.getName();
                List<String> strings = formValues.get(name);
                if (writeMethod != null && strings != null && strings.size() == 1) {
                    writeMethod.invoke(ret,
                            DataType.asType(propertyDescriptor.getPropertyType(), strings.get(0))); // TODO lists, consume values from ctor
                }
            }
            return ret;
        } catch (Exception e) {
            throw new RuntimeException("Failed to instantiate bean " + clazz.getName(), e);
        }
    }
}

From source file:org.openehr.validation.DataValidatorImpl.java

/**
 * Retorna construtor de um parametro {@link String}
 * @param klass//from  w w  w . ja  v a2s .c o  m
 * @return
 * @throws SecurityException
 */
private Constructor getConstructorWithStringArgument(Class klass) {
    Constructor constructor = null;

    for (Constructor constr : klass.getConstructors()) {
        if (constr.getParameterTypes().length == 1 && constr.getParameterTypes()[0].equals(String.class)) {
            constructor = constr;
            break;
        }
    }
    return constructor;
}