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:lite.flow.runtime.kiss.ComponentUtil.java

private static Object[] buildConstructorArgs(Constructor<?> constructor, Map<String, Object> resources,
        Map<String, Object> parameters) {
    requireNonNull(resources, "ComponentUtil.buildConstructorArgs resources should not be null");
    requireNonNull(parameters, "ComponentUtil.buildConstructorArgs parameters should not be null");

    constructor.getParameterTypes();

    Parameter[] consParameters = constructor.getParameters();
    if (consParameters == null || consParameters.length < 1)
        return null;

    Object[] args = new Object[consParameters.length];
    for (int i = 0; i < consParameters.length; i++) {
        Parameter consParam = consParameters[i];
        Object consParamvalue = getConsParamvalue(consParam, resources, parameters);
        args[i] = consParamvalue;//from w ww. java  2 s . c  om
    }

    return args;
}

From source file:org.thaliproject.p2p.btconnectorlib.internal.bluetooth.BluetoothUtils.java

/**
 * Creates a new Bluetooth socket with the given service record UUID and the given channel/port.
 * @param bluetoothDevice The Bluetooth device.
 * @param serviceRecordUuid The service record UUID.
 * @param channelOrPort The RFCOMM channel or L2CAP psm to use.
 * @param secure If true, will try to create a secure RFCOMM socket. If false, will try to create an insecure one.
 * @return A new Bluetooth socket with the specified channel/port or null in case of a failure.
 *///from   w ww.  j  a  va  2  s. c  o  m
public static BluetoothSocket createBluetoothSocketToServiceRecord(BluetoothDevice bluetoothDevice,
        UUID serviceRecordUuid, int channelOrPort, boolean secure) {
    Constructor[] bluetoothSocketConstructors = BluetoothSocket.class.getDeclaredConstructors();
    Constructor bluetoothSocketConstructor = null;

    for (Constructor constructor : bluetoothSocketConstructors) {
        Class<?>[] parameterTypes = constructor.getParameterTypes();
        boolean takesBluetoothDevice = false;
        boolean takesParcelUuid = false;

        for (Class<?> parameterType : parameterTypes) {
            if (parameterType.equals(BluetoothDevice.class)) {
                takesBluetoothDevice = true;
            } else if (parameterType.equals(ParcelUuid.class)) {
                takesParcelUuid = true;
            }
        }

        if (takesBluetoothDevice && takesParcelUuid) {
            // We found the right constructor
            bluetoothSocketConstructor = constructor;
            break;
        }
    }

    // This is the constructor we should now have:
    // BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, BluetoothDevice device,
    //      int port, ParcelUuid uuid) throws IOException

    // Create the parameters for the constructor
    Object[] parameters = new Object[] { Integer.valueOf(1), // BluetoothSocket.TYPE_RFCOMM
            Integer.valueOf(-1), Boolean.valueOf(secure), Boolean.valueOf(secure), bluetoothDevice,
            Integer.valueOf(channelOrPort), new ParcelUuid(serviceRecordUuid) };

    bluetoothSocketConstructor.setAccessible(true);
    BluetoothSocket bluetoothSocket = null;

    try {
        bluetoothSocket = (BluetoothSocket) bluetoothSocketConstructor.newInstance(parameters);
        Log.d(TAG, "createBluetoothSocketToServiceRecord: Socket created with channel/port " + channelOrPort);
    } catch (Exception e) {
        Log.e(TAG, "createBluetoothSocketToServiceRecord: Failed to create a new Bluetooth socket instance: "
                + e.getMessage(), e);
    }

    return bluetoothSocket;
}

From source file:org.openehealth.ipf.commons.lbs.utils.NiceClass.java

/**
 * Ensures that a constructors of a class is null safe.
 * @param obj/*from www . ja v a2s.c om*/
 *          object to test
 * @param args
 *          dummy arguments of all different parameter types that the constructor has
 * @param optional
 *          optional dummy arguments that can also be set to {@code null} without breaking
 *          null-safety
 * @throws any thrown exception that were not expected. Never an {@link IllegalArgumentException}.
 */
public static void checkConstructorIsNullSafe(Constructor<?> constructor, List<?> args, List<?> optional)
        throws Exception {
    log.info("checked " + constructor);

    constructor.setAccessible(true);

    Class<?>[] parameterTypes = constructor.getParameterTypes();
    Object[] parameterValues = getParameterValues(parameterTypes, args);

    for (int idx = 0; idx < parameterValues.length; ++idx) {
        if (!isOptional(constructor.getName(), idx, optional, parameterValues[idx])) {
            Object[] parameterValuesWithNull = Arrays.copyOf(parameterValues, parameterValues.length);
            parameterValuesWithNull[idx] = null;

            try {
                constructor.newInstance(parameterValuesWithNull);
                fail("Should throw an " + IllegalArgumentException.class.getSimpleName());
            } catch (InvocationTargetException e) {
                assertEquals(IllegalArgumentException.class, e.getCause().getClass());
            }
        }
    }
}

From source file:gov.nih.nci.firebird.selenium2.pages.util.FirebirdTableUtils.java

public static <T extends TableListing> List<T> transformDataTableRows(final AbstractLoadableComponent<?> parent,
        WebElement table, Class<T> tableListingClass) {
    try {//from  ww  w. j a  v a  2s . c  om
        final Constructor<T> constructor = getConstructor(parent, tableListingClass);

        Function<WebElement, T> transformation = new Function<WebElement, T>() {
            @Override
            public T apply(WebElement row) {
                try {
                    if (constructor.getParameterTypes().length == 2) {
                        return constructor.newInstance(parent, row);
                    } else {
                        return constructor.newInstance(row);
                    }
                } catch (Exception e) {
                    fail(ExceptionUtils.getRootCauseMessage(e));
                }
                return null;
            }
        };
        return JQueryUtils.transformDataTableRows(table, transformation);
    } catch (Exception e) {
        fail(ExceptionUtils.getRootCauseMessage(e));
    }
    return null;
}

From source file:ReflectionTest.java

/**
 * Prints all constructors of a class//  w w w.  j  a  va  2s .com
 * @param cl a class
 */
public static void printConstructors(Class cl) {
    Constructor[] constructors = cl.getDeclaredConstructors();

    for (Constructor c : constructors) {
        String name = c.getName();
        System.out.print("   ");
        String modifiers = Modifier.toString(c.getModifiers());
        if (modifiers.length() > 0)
            System.out.print(modifiers + " ");
        System.out.print(name + "(");

        // print parameter types
        Class[] paramTypes = c.getParameterTypes();
        for (int j = 0; j < paramTypes.length; j++) {
            if (j > 0)
                System.out.print(", ");
            System.out.print(paramTypes[j].getName());
        }
        System.out.println(");");
    }
}

From source file:edu.brown.utils.ClassUtil.java

/**
 * Grab the constructor for the given target class with the provided input parameters.
 * This method will first try to find an exact match for the parameters, and if that
 * fails then it will be smart and try to find one with the input parameters super classes. 
 * @param <T>/*from w  w  w  .j  a va  2 s  . c  om*/
 * @param target_class
 * @param params
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> Constructor<T> getConstructor(Class<T> target_class, Class<?>... params) {
    NoSuchMethodException error = null;
    try {
        return (target_class.getConstructor(params));
    } catch (NoSuchMethodException ex) {
        // The first time we get this it can be ignored
        // We'll try to be nice and find a match for them
        error = ex;
    }
    assert (error != null);

    if (debug.val) {
        LOG.debug("TARGET CLASS:  " + target_class);
        LOG.debug("TARGET PARAMS: " + Arrays.toString(params));
    }

    final int num_params = (params != null ? params.length : 0);
    List<Class<?>> paramSuper[] = (List<Class<?>>[]) new List[num_params];
    for (int i = 0; i < num_params; i++) {
        paramSuper[i] = ClassUtil.getSuperClasses(params[i]);
        if (debug.val)
            LOG.debug("  SUPER[" + params[i].getSimpleName() + "] => " + paramSuper[i]);
    } // FOR

    for (Constructor<?> c : target_class.getConstructors()) {
        Class<?> cTypes[] = c.getParameterTypes();
        if (debug.val) {
            LOG.debug("CANDIDATE: " + c);
            LOG.debug("CANDIDATE PARAMS: " + Arrays.toString(cTypes));
        }
        if (params.length != cTypes.length)
            continue;

        for (int i = 0; i < num_params; i++) {
            List<Class<?>> cSuper = ClassUtil.getSuperClasses(cTypes[i]);
            if (debug.val)
                LOG.debug("  SUPER[" + cTypes[i].getSimpleName() + "] => " + cSuper);
            if (CollectionUtils.intersection(paramSuper[i], cSuper).isEmpty() == false) {
                return ((Constructor<T>) c);
            }
        } // FOR (param)
    } // FOR (constructors)
    throw new RuntimeException("Failed to retrieve constructor for " + target_class.getSimpleName(), error);
}

From source file:io.coala.factory.ClassUtil.java

/**
 * @param returnType the type of the stored property value
 * @param args the arguments for construction
 * @return the property value's class instantiated
 * @throws CoalaException if the property's value is no instance of
 *             valueClass//from w w  w .  j a  v  a 2s  .  c o m
 */
@SuppressWarnings("unchecked")
public static <T> T instantiate(final Class<T> returnType, final Object... args) throws CoalaException {
    if (returnType == null)
        throw CoalaExceptionFactory.VALUE_NOT_SET.create("returnType");

    final Class<?>[] argTypes = new Class<?>[args.length];
    for (int i = 0; i < args.length; i++)
        argTypes[i] = args[i] == null ? null : args[i].getClass();

    for (Constructor<?> constructor : returnType.getConstructors()) {
        final Class<?>[] paramTypes = constructor.getParameterTypes();
        if (paramTypes.length != args.length) // different argument count,
        // try next constructor
        {
            continue;
        }

        boolean match = true;
        for (int i = 0; match && i < paramTypes.length; i++) {
            if (args[i] == null && !paramTypes[i].isPrimitive())
                argTypes[i] = paramTypes[i];
            else if (!isAssignableFrom(paramTypes[i], argTypes[i]))
                match = false;
        }

        if (!match) // no matching parameter types, try next constructor
        {
            continue;
        }

        try {
            return (T) constructor.newInstance(args);
        } catch (final InvocationTargetException exception) {
            // exception caused by the constructor itself, pass cause thru
            throw exception.getCause() instanceof CoalaException ? (CoalaException) exception.getCause()
                    : CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType,
                            Arrays.asList(argTypes));
        } catch (final Exception exception) {
            throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(exception, returnType, Arrays.asList(argTypes));
        }
    }
    throw CoalaExceptionFactory.INCONSTRUCTIBLE.create(returnType, Arrays.asList(argTypes));
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return signature for given {@link Constructor}. This signature is not same signature as in JVM or JDT,
 *         just some string that unique identifies constructor in its {@link Class}.
 *///from  ww  w  .  j av  a  2s .co m
public static String getConstructorSignature(Constructor<?> constructor) throws Exception {
    Assert.isNotNull(constructor);
    return getConstructorSignature(constructor.getParameterTypes());
}

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  w  w . ja v  a  2  s .  c o  m*/
            }
        }
    }
    throw new RuntimeException(
            c + " does not have a public constructor with " + numArgs + " matching parameter type(s).");
}

From source file:xiaofei.library.hermes.util.TypeUtils.java

public static Constructor<?> getConstructor(Class<?> clazz, Class<?>[] parameterTypes) throws HermesException {
    Constructor<?> result = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    for (Constructor<?> constructor : constructors) {
        if (classAssignable(constructor.getParameterTypes(), parameterTypes)) {
            if (result != null) {
                throw new HermesException(ErrorCodes.TOO_MANY_MATCHING_CONSTRUCTORS_FOR_CREATING_INSTANCE,
                        "The class " + clazz.getName() + " has too many constructors whose "
                                + " parameter types match the required types.");
            } else {
                result = constructor;/* w  w  w.j  a v  a  2  s . c  o m*/
            }
        }
    }
    if (result == null) {
        throw new HermesException(ErrorCodes.CONSTRUCTOR_NOT_FOUND, "The class " + clazz.getName()
                + " do not have a constructor whose " + " parameter types match the required types.");
    }
    return result;
}