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.mycore.common.MCRUtils.java

@SafeVarargs
public static Exception unwrapExCeption(Exception e, Class<? extends Exception>... classes) {
    if (classes.length == 0) {
        return e;
    }/*  www . j  a  v a 2s.com*/
    Class<? extends Exception> mainExceptionClass = classes[0];
    Throwable check = e;
    for (Class<? extends Exception> instChk : classes) {
        if (instChk.isInstance(check)) {
            return (Exception) check;
        }
        check = check.getCause();
        if (check == null) {
            break;
        }
    }
    @SuppressWarnings("unchecked")
    Constructor<? extends Exception>[] constructors = (Constructor<? extends Exception>[]) mainExceptionClass
            .getConstructors();
    for (Constructor<? extends Exception> c : constructors) {
        Class<?>[] parameterTypes = c.getParameterTypes();
        try {
            if (parameterTypes.length == 0) {
                Exception exception = c.newInstance((Object[]) null);
                exception.initCause(e);
                return exception;
            }
            if (parameterTypes.length == 1 && parameterTypes[0].isAssignableFrom(mainExceptionClass)) {
                return c.newInstance(e);
            }
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException ex) {
            LOGGER.warn("Exception while initializing exception " + mainExceptionClass.getCanonicalName(), ex);
            return e;
        }
    }
    LOGGER.warn("Could not instanciate Exception " + mainExceptionClass.getCanonicalName());
    return e;
}

From source file:org.echocat.jomon.process.daemon.ProcessDaemonRepository.java

@Nonnull
protected List<Constructor<D>> getPotentialConstructorsSortedFor(@Nonnull Class<? extends D> type) {
    // noinspection unchecked
    final List<Constructor<D>> potentialConstructors = asList((Constructor<D>[]) type.getConstructors());
    sort(potentialConstructors, BY_PARAMETER_COUNT);
    return potentialConstructors;
}

From source file:org.jboss.spring.aop.JBossAopProxy.java

/**
 * Create the target.//from w w  w.j a  v a 2 s . c om
 *
 * @param cache the cache
 * @param params the parameters
 * @return target instance
 * @throws Throwable for any error
 */
private Object createTarget(ContainerCache cache, AOPProxyFactoryParameters params) throws Throwable {
    Advisor advisor = cache.getAdvisor();
    if (advisor != null) {
        org.jboss.aop.ConstructorInfo aopinfo = findAopConstructorInfo(advisor);

        Interceptor[] interceptors = (aopinfo != null) ? aopinfo.getInterceptors() : null;

        if (interceptors != null) {
            ConstructorInvocation inv = new ConstructorInvocation(aopinfo, aopinfo.getInterceptors());
            inv.setArguments(getArguments());
            return inv.invokeNext();
        }

        if (constructorInfo.getParameterTypes().length > 0) {
            Constructor<?> constructor = null;
            if (aopinfo == null) {
                //Fall back to using the class;
                Class<?> clazz = advisor.getClazz();
                Constructor<?>[] ctors = clazz.getConstructors();
                for (Constructor<?> ctor : ctors) {
                    if (matchConstructor(ctor)) {
                        constructor = ctor;
                        break;
                    }
                }
            } else {
                constructor = aopinfo.getConstructor();
            }
            params.setCtor(constructor.getParameterTypes(), getArguments());
        }
    }

    return constructorInfo.newInstance(getArguments());
}

From source file:it.tidalwave.northernwind.frontend.impl.ui.ViewBuilder.java

/*******************************************************************************************************************
 *
 *
 ******************************************************************************************************************/
public ViewBuilder(final @Nonnull Class<?> viewClass, final @Nonnull Class<?> viewControllerClass)
        throws NoSuchMethodException, InvocationTargetException, InstantiationException,
        IllegalArgumentException, IllegalAccessException, SecurityException {
    viewConstructor = viewClass.getConstructors()[0];
    viewControllerConstructor = viewControllerClass.getConstructors()[0];
}

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

/**
 * ???/*from w w  w.j a va  2 s.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:org.getspout.spoutapi.packet.PacketAddonData.java

@SuppressWarnings("unchecked")
@Override//  w w  w  .  j  a v  a2 s. com
public void readData(SpoutInputStream input) throws IOException {
    String packetName = input.readString();
    try {
        Class<? extends AddonPacket> packetClass = AddonPacket.getPacketFromId(packetName);
        Constructor<? extends AddonPacket> constructor = null;
        Constructor<? extends AddonPacket>[] constructors = (Constructor<? extends AddonPacket>[]) packetClass
                .getConstructors();
        for (Constructor<? extends AddonPacket> c : constructors) {
            if (c.getGenericParameterTypes().length == 0) {
                constructor = c;
                break;
            }
        }
        packet = constructor.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    int size = input.readInt();
    compressed = input.readBoolean();
    data = new byte[size];
    input.read(data);
}

From source file:org.forgerock.openidm.selfservice.impl.SelfService.java

private ProgressStageProvider newProgressStageProvider(final Client httpClient) {
    return new ProgressStageProvider() {

        @Override/*from w ww .  j  a v  a2 s  . com*/
        public ProgressStage<StageConfig> get(Class<? extends ProgressStage<StageConfig>> progressStageClass) {
            Constructor<?>[] constructors = progressStageClass.getConstructors();

            if (constructors.length > 1) {
                throw new StageConfigException(
                        "Only expected one constructor for the configured progress stage "
                                + progressStageClass);
            }

            try {
                Constructor<? extends ProgressStage<StageConfig>> constructor = progressStageClass
                        .getConstructor(constructors[0].getParameterTypes());

                Object[] parameters = getParameters(constructor);
                return constructor.newInstance(parameters);

            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException
                    | InstantiationException e) {
                throw new StageConfigException("Unable to instantiate the configured progress stage", e);
            }
        }

        private Object[] getParameters(Constructor<?> constructor) {
            Class<?>[] parameterTypes = constructor.getParameterTypes();
            Object[] parameters = new Object[parameterTypes.length];

            for (int i = 0; i < parameterTypes.length; i++) {
                if (parameterTypes[i].equals(ConnectionFactory.class)) {
                    parameters[i] = connectionFactory;
                } else if (parameterTypes[i].equals(Client.class)) {
                    parameters[i] = httpClient;
                } else {
                    throw new StageConfigException(
                            "Unexpected parameter type for configured progress stage " + parameters[i]);
                }
            }

            return parameters;
        }
    };
}

From source file:de.gebatzens.ggvertretungsplan.GGApp.java

public void createProvider(String id) {
    Log.w("ggvp", "createProvider " + id);
    Class<? extends VPProvider> clas = mProviderList.get(id);
    if (clas == null)
        throw new RuntimeException("Provider for " + id + " not found");

    try {/*  w w  w  . j a  v  a  2s  .c  om*/
        provider = (VPProvider) clas.getConstructors()[0].newInstance(this, id);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.getspout.spout.packet.PacketAddonData.java

@SuppressWarnings("unchecked")
public void readData(DataInputStream input) throws IOException {
    String id = PacketUtil.readString(input);

    boolean sandboxed = SpoutClient.isSandboxed();
    SpoutClient.enableSandbox();//from w ww  .  j av a 2s  .  co  m

    try {
        Class<? extends AddonPacket> packetClass = AddonPacket.getPacketFromId(id);
        Constructor<? extends AddonPacket> constructor = null;
        Constructor<? extends AddonPacket>[] constructors = (Constructor<? extends AddonPacket>[]) packetClass
                .getConstructors();
        for (Constructor<? extends AddonPacket> c : constructors) {
            if (c.getGenericParameterTypes().length == 0) {
                constructor = c;
                break;
            }
        }
        packet = constructor.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (!sandboxed) {
        SpoutClient.disableSandbox();
    }

    int size = input.readInt();
    compressed = input.readBoolean();
    data = new byte[size];
    input.readFully(data);
}

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

public static Constructor<?> getBeanConstructor(Class<?> targetClass, Class<?> sourceClass)
        throws InvalidArgumentException {
    try {/*from w  ww . ja  v a 2s  . c  om*/
        Constructor<?> c = targetClass.getConstructor(sourceClass);
        if (c != null)
            return c;

    } catch (NoSuchMethodException | SecurityException e) {
        mLogger.info("Exception getting constructors for: " + targetClass.getName(), e);
        return null;
    }

    Constructor<?>[] cs = targetClass.getConstructors();

    for (Constructor<?> c : cs) {
        Class<?>[] params = c.getParameterTypes();
        if (params.length == 1) {
            int convert = canConvertClass(sourceClass, params[0]);
            if (convert >= 0)
                return c;
        }
    }
    return null;
}