Example usage for java.lang.reflect Constructor getParameterTypes

List of usage examples for java.lang.reflect Constructor getParameterTypes

Introduction

In this page you can find the example usage for java.lang.reflect Constructor getParameterTypes.

Prototype

@Override
public Class<?>[] getParameterTypes() 

Source Link

Usage

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * Adds {@link ConstructorDescription} for given {@link ComponentDescription}.
 *///  w ww . ja  va 2 s.co m
private static void addConstructors(IJavaProject javaProject, ComponentDescription componentDescription)
        throws Exception {
    Class<?> componentClass = componentDescription.getComponentClass();
    for (Constructor<?> constructor : componentClass.getDeclaredConstructors()) {
        constructor.setAccessible(true);
        ConstructorDescription constructorDescription = new ConstructorDescription(componentClass);
        // add parameter descriptions of constructor
        for (Class<?> parameterType : constructor.getParameterTypes()) {
            addParameter(constructorDescription, parameterType);
        }
        // OK, add constructor description
        constructorDescription.postProcess();
        componentDescription.addConstructor(constructorDescription);
    }
}

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 ww  w .  ja  va 2 s  .  c  o m*/
        }
    }

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

From source file:org.pircbotx.hooks.events.MassEventTest.java

@Test(dependsOnMethods = "singleConstructorTest", dataProvider = "eventObjectDataProvider", dataProviderClass = TestUtils.class, description = "Verify number of class fields and number of constructor params match")
public void constructorParamToFieldTest(Class<?> event) {
    if (event == WhoisEvent.class) {
        //This uses a builder
        return;//from ww w  .  j  a  v  a  2s.  co m
    }

    //Manually count fields to exclude synthetic ones
    int fieldCount = 0;
    for (Field curField : event.getDeclaredFields())
        if (TestUtils.isRealMember(curField))
            fieldCount++;
    Constructor constructor = event.getDeclaredConstructors()[0];
    //(subtract one parameter to account for bot)
    assertEquals(constructor.getParameterTypes().length - 1, fieldCount,
            wrapClass(event,
                    "Number of constructor parameters don't match number of fields" + SystemUtils.LINE_SEPARATOR
                            + "Constructor params [" + StringUtils.join(constructor.getParameterTypes(), ", ")
                            + "]"));
}

From source file:com.mayabot.thriftpool.utils.ReflectUtils.java

/**
 * ???/*from  ww w . j  ava 2s. co  m*/
 * 
 * @param clazz 
 * @param methodName ??method1(int, String)?????????method2
 * @return 
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException  
 * @throws IllegalStateException ???????
 */
//   public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes)
//           throws NoSuchMethodException, ClassNotFoundException {
//       String signature = clazz.getName() + "." + methodName;
//        if(parameterTypes != null && parameterTypes.length > 0){
//            signature += StringUtils.join(parameterTypes);
//        }
//        Method method = Signature_METHODS_CACHE.get(signature);
//        if(method != null){
//            return method;
//        }
//       if (parameterTypes == null) {
//            List<Method> finded = new ArrayList<Method>();
//            for (Method m : clazz.getMethods()) {
//                if (m.getName().equals(methodName)) {
//                    finded.add(m);
//                }
//            }
//            if (finded.isEmpty()) {
//                throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
//            }
//            if(finded.size() > 1) {
//                String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.",
//                        methodName, clazz.getName(), finded.size());
//                throw new IllegalStateException(msg);
//            }
//            method = finded.get(0);
//        } else {
//            Class<?>[] types = new Class<?>[parameterTypes.length];
//            for (int i = 0; i < parameterTypes.length; i ++) {
//                types[i] = ReflectUtils.name2class(parameterTypes[i]);
//            }
//            method = clazz.getMethod(methodName, types);
//            
//        }
//       Signature_METHODS_CACHE.put(signature, method);
//        return method;
//   }

//    public static Method findMethodByMethodName(Class<?> clazz, String methodName)
//          throws NoSuchMethodException, ClassNotFoundException {
//       return findMethodByMethodSignature(clazz, methodName, null);
//    }

public static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType) throws NoSuchMethodException {
    Constructor<?> targetConstructor;
    try {
        targetConstructor = clazz.getConstructor(new Class<?>[] { paramType });
    } catch (NoSuchMethodException e) {
        targetConstructor = null;
        Constructor<?>[] constructors = clazz.getConstructors();
        for (Constructor<?> constructor : constructors) {
            if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 1
                    && constructor.getParameterTypes()[0].isAssignableFrom(paramType)) {
                targetConstructor = constructor;
                break;
            }
        }
        if (targetConstructor == null) {
            throw e;
        }
    }
    return targetConstructor;
}

From source file:com.glaf.core.util.ReflectUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> Constructor<T> findMatchingConstructor(Class<T> clazz, Object[] args) {
    for (Constructor constructor : clazz.getDeclaredConstructors()) {
        if (matches(constructor.getParameterTypes(), args)) {
            return constructor;
        }//from ww w  .  ja  v a  2  s  .c  o  m
    }
    return null;
}

From source file:de.itsvs.cwtrpc.security.SimpleRpcAuthenticationFailureHandler.java

@SuppressWarnings("unchecked")
protected <T extends Exception> Constructor<T> getMessageConstructor(Class<T> exception) {
    for (Constructor<?> constructor : exception.getConstructors()) {
        if ((constructor.getParameterTypes().length == 1)
                && String.class.equals(constructor.getParameterTypes()[0])) {
            return ((Constructor<T>) constructor);
        }/*from  w w w . j  av a  2 s  .  c  om*/
    }
    return null;
}

From source file:hu.bme.mit.sette.common.validator.reflection.ConstructorValidator.java

/**
 * Sets the required parameter count for the constructor.
 *
 * @param parameterCount//from  w  w  w  .  j a va2  s .c om
 *            the required parameter count for the constructor.
 * @return this object
 */
public ConstructorValidator parameterCount(final int parameterCount) {
    Validate.isTrue(parameterCount >= 0, "The required parameter count must be " + "a non-negative number");

    if (getSubject() != null) {
        Constructor<?> constructor = getSubject();

        if (constructor.getParameterTypes().length != parameterCount) {
            if (parameterCount == 0) {
                this.addException("The constructor must not have " + "any parameters");
            } else if (parameterCount == 1) {
                this.addException("The constructor must have " + "exactly 1 parameter");
            } else {
                this.addException(
                        String.format("The constructor must have " + "exactly %d parameters", parameterCount));
            }
        }
    }

    return this;
}

From source file:com.cloudera.livy.client.common.TestHttpMessages.java

/**
 * Tests that all defined messages can be serialized and deserialized using Jackson.
 *///w  ww.  ja v a 2s .co  m
@Test
public void testMessageSerialization() throws Exception {
    ObjectMapper mapper = new ObjectMapper();

    for (Class<?> msg : HttpMessages.class.getClasses()) {
        if (msg.isInterface()) {
            continue;
        }

        String name = msg.getSimpleName();

        Constructor c = msg.getConstructors()[0];
        Object[] params = new Object[c.getParameterTypes().length];
        Type[] genericTypes = c.getGenericParameterTypes();
        for (int i = 0; i < params.length; i++) {
            params[i] = dummyValue(c.getParameterTypes()[i], genericTypes[i]);
        }

        Object o1 = c.newInstance(params);
        byte[] serialized = mapper.writeValueAsBytes(o1);
        Object o2 = mapper.readValue(serialized, msg);

        assertNotNull("could not deserialize " + name, o2);
        for (Field f : msg.getFields()) {
            checkEquals(name, f, o1, o2);
        }
    }

}

From source file:org.batoo.common.reflect.ReflectHelper.java

private static ConstructorAccessor createConstructorImpl(Constructor<?> constructor) {
    try {//from  w  w w  . java2  s .  c  o m
        final Class<?> magClass = Class.forName("sun.reflect.MethodAccessorGenerator");
        final Constructor<?> c = magClass.getDeclaredConstructors()[0];
        final Method generateMethod = magClass.getMethod("generateConstructor", Class.class, Class[].class,
                Class[].class, Integer.TYPE);

        ReflectHelper.setAccessible(c, true);
        ReflectHelper.setAccessible(generateMethod, true);

        try {
            final Object mag = c.newInstance();

            return new SunConstructorAccessor(
                    generateMethod.invoke(mag, constructor.getDeclaringClass(), constructor.getParameterTypes(),
                            constructor.getExceptionTypes(), constructor.getModifiers()));
        } finally {
            ReflectHelper.setAccessible(c, false);
            ReflectHelper.setAccessible(generateMethod, false);
        }
    } catch (final Exception e) {
        throw new RuntimeException("Constructor generation failed", e);
    }
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * TODO move into {@link ReflectionUtils}.
 * //from www  .j  a  va  2  s  .c o  m
 * @return the source for creating {@link Object} using given {@link Constructor} with values
 *         default for type of each argument.
 */
public static String getDefaultConstructorInvocation(Constructor<?> constructor) {
    // prepare Class
    Class<?> componentClass = constructor.getDeclaringClass();
    String componentClassName = ReflectionUtils.getCanonicalName(componentClass);
    // prepare arguments
    String arguments;
    {
        StringBuilder buffer = new StringBuilder();
        for (Class<?> parameter : constructor.getParameterTypes()) {
            String parameterName = ReflectionUtils.getCanonicalName(parameter);
            buffer.append(AstParser.getDefaultValue(parameterName));
            buffer.append(", ");
        }
        arguments = StringUtils.removeEnd(buffer.toString(), ", ");
    }
    // prepare source
    return "new " + componentClassName + "(" + arguments + ")";
}