Example usage for java.lang Class getDeclaredConstructor

List of usage examples for java.lang Class getDeclaredConstructor

Introduction

In this page you can find the example usage for java.lang Class getDeclaredConstructor.

Prototype

@CallerSensitive
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Constructor object that reflects the specified constructor of the class or interface represented by this Class object.

Usage

From source file:com.google.apphosting.vmruntime.VmApiProxyDelegate.java

private RuntimeException constructException(String exceptionClassName, String message, String packageName,
        String methodName) {//from w  ww .j a va2  s . c om
    try {
        Class<?> c = Class.forName(exceptionClassName);
        Constructor<?> constructor = c.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        return (RuntimeException) constructor.newInstance(message);
    } catch (Exception e) {
        return new RPCFailedException(packageName, methodName);
    }
}

From source file:org.apache.phoenix.queryserver.server.Main.java

@Override
public int run(String[] args) throws Exception {
    logProcessInfo(getConf());//from ww  w. j a va2 s  .  c om
    try {
        // handle secure cluster credentials
        if ("kerberos".equalsIgnoreCase(getConf().get(HBASE_SECURITY_CONF_KEY))) {
            String hostname = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
                    getConf().get(DNS_INTERFACE_KEY, "default"), getConf().get(DNS_NAMESERVER_KEY, "default")));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Login to " + hostname + " using " + getConf().get(KEYTAB_FILENAME_KEY)
                        + " and principal " + getConf().get(KERBEROS_PRINCIPAL_KEY) + ".");
            }
            SecurityUtil.login(getConf(), KEYTAB_FILENAME_KEY, KERBEROS_PRINCIPAL_KEY, hostname);
            LOG.info("Login successful.");
        }
        Class<? extends PhoenixMetaFactory> factoryClass = getConf().getClass(QUERY_SERVER_META_FACTORY_KEY,
                PhoenixMetaFactoryImpl.class, PhoenixMetaFactory.class);
        int port = getConf().getInt(QUERY_SERVER_HTTP_PORT_KEY, DEFAULT_HTTP_PORT);
        LOG.debug("Listening on port " + port);
        PhoenixMetaFactory factory = factoryClass.getDeclaredConstructor(Configuration.class)
                .newInstance(getConf());
        Meta meta = factory.create(Arrays.asList(args));
        Service service = new LocalService(meta);
        server = new HttpServer(port, new AvaticaHandler(service));
        server.start();
        runningLatch.countDown();
        server.join();
        return 0;
    } catch (Throwable t) {
        LOG.fatal("Unrecoverable service error. Shutting down.", t);
        this.t = t;
        return -1;
    }
}

From source file:org.unitils.util.ReflectionUtils.java

/**
 * Creates an instance of the given type
 * //from   w w w .j a v  a  2 s . c o m
 * @param <T>
 *            The type of the instance
 * @param type
 *            The type of the instance
 * @param bypassAccessibility
 *            If true, no exception is thrown if the parameterless
 *            constructor is not public
 * @param argumentTypes
 *            The constructor arg types, not null
 * @param arguments
 *            The constructor args, not null
 * @return An instance of this type
 * @throws UnitilsException
 *             If an instance could not be created
 */
public static <T> T createInstanceOfType(Class<T> type, boolean bypassAccessibility, Class[] argumentTypes,
        Object[] arguments) {

    if (type.isMemberClass() && !isStatic(type.getModifiers())) {
        throw new UnitilsException(
                "Creation of an instance of a non-static innerclass is not possible using reflection. The type "
                        + type.getSimpleName()
                        + " is only known in the context of an instance of the enclosing class "
                        + type.getEnclosingClass().getSimpleName()
                        + ". Declare the innerclass as static to make construction possible.");
    }
    try {
        Constructor<T> constructor = type.getDeclaredConstructor(argumentTypes);
        if (bypassAccessibility) {
            constructor.setAccessible(true);
        }
        return constructor.newInstance(arguments);

    } catch (InvocationTargetException e) {
        throw new UnitilsException("Error while trying to create object of class " + type.getName(),
                e.getCause());

    } catch (Exception e) {
        throw new UnitilsException("Error while trying to create object of class " + type.getName(), e);
    }
}

From source file:com.microsoft.azure.storage.core.Utility.java

public static void checkNullaryCtor(Class<?> clazzType) {
    Constructor<?> ctor = null;
    try {/*from ww w .j a  v  a2  s . co m*/
        ctor = clazzType.getDeclaredConstructor((Class<?>[]) null);
    } catch (Exception e) {
        throw new IllegalArgumentException(SR.MISSING_NULLARY_CONSTRUCTOR);
    }

    if (ctor == null) {
        throw new IllegalArgumentException(SR.MISSING_NULLARY_CONSTRUCTOR);
    }
}

From source file:org.omnaest.utils.reflection.ReflectionUtils.java

/**
 * Returns the {@link Constructor} for the given {@link Class} type and parameter types
 * //  www  . j  a v  a  2s . co  m
 * @param type
 * @param parameterTypes
 * @return
 */
@SuppressWarnings("unchecked")
public static <B> Constructor<B> constructorFor(Class<? extends B> type, Class<?>... parameterTypes) {
    //
    Constructor<B> constructor = null;

    //
    try {
        //
        constructor = (Constructor<B>) type.getDeclaredConstructor(parameterTypes);
    } catch (Exception e) {
        try {
            constructor = (Constructor<B>) type.getConstructor(parameterTypes);
        } catch (Exception e2) {
            try {
                constructor = (Constructor<B>) resolveConstructorFor(type, parameterTypes);
            } catch (Exception e3) {
            }
        }
    }

    //
    return constructor;
}

From source file:com.snaplogic.snaps.uniteller.BaseService.java

@Override
protected void process(Document document, String inputViewName) {
    try {//w ww  . j av a2s  .c o  m
        AccountBean bean = account.connect();
        String UFSConfigFilePath = urlEncoder.validateAndEncodeURI(bean.getConfigFilePath(), PATTERN, null)
                .toString();
        String UFSSecurityFilePath = urlEncoder
                .validateAndEncodeURI(bean.getSecurityPermFilePath(), PATTERN, null).toString();
        /* instantiating USFCreationClient */
        Class<?> CustomUSFCreationClient = Class.forName(UFS_FOLIO_CREATION_CLIENT_PKG_URI);
        Constructor<?> constructor = CustomUSFCreationClient
                .getDeclaredConstructor(new Class[] { IUFSConfigMgr.class, IUFSSecurityMgr.class });
        Object USFCreationClientObj = constructor.newInstance(CustomUFSConfigMgr.getInstance(UFSConfigFilePath),
                CustomUFSSecurityMgr.getInstance(UFSSecurityFilePath));
        Method setAutoUpdatePsw = CustomUSFCreationClient.getDeclaredMethod("setAutoUpdatePsw", Boolean.TYPE);
        setAutoUpdatePsw.invoke(USFCreationClientObj, autoUpdatePsw);
        /* Preparing the request for USF */
        Object data;
        if (document != null && (data = document.get()) != null) {
            if (data instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) data;
                Class<?> UFSRequest = Class.forName(getUFSReqClassType());
                Object UFSRequestObj = UFSRequest.newInstance();
                Object inputFieldValue = null;
                Calendar cal = Calendar.getInstance();
                for (Method method : UFSRequest.getDeclaredMethods()) {
                    if (isSetter(method)
                            && (inputFieldValue = map.get(method.getName().substring(3))) != null) {
                        try {
                            String paramType = method.getParameterTypes()[0].getName();
                            if (paramType.equalsIgnoreCase(String.class.getName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj), String.valueOf(inputFieldValue));
                            } else if (paramType.equalsIgnoreCase(Double.class.getSimpleName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Double.parseDouble(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(INT)) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Integer.parseInt(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(Calendar.class.getName())) {
                                try {
                                    cal.setTime(sdtf.parse(String.valueOf(inputFieldValue)));
                                } catch (ParseException pe1) {
                                    try {
                                        cal.setTime(sdf.parse(String.valueOf(inputFieldValue)));
                                    } catch (ParseException pe) {
                                        writeToErrorView(
                                                String.format(DATE_PARSER_ERROR, DATETIME_FORMAT, DATE_FORMAT),
                                                pe.getMessage(), ERROR_RESOLUTION, pe);
                                    }
                                }
                                method.invoke(UFSRequest.cast(UFSRequestObj), cal);
                            }
                        } catch (IllegalArgumentException iae) {
                            writeToErrorView(String.format(ILLEGAL_ARGS_EXE, method.getName()),
                                    iae.getMessage(), ERROR_RESOLUTION, iae);
                        } catch (InvocationTargetException ite) {
                            writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(),
                                    ERROR_RESOLUTION, ite);
                        }
                    }
                }
                /* Invoking the request over USFCreationClient */
                Object UFSResponseObj = null;
                Method creationClientMethod = CustomUSFCreationClient
                        .getMethod(getCamelCaseForMethod(resourceType), UFSRequest);
                try {
                    UFSResponseObj = creationClientMethod.invoke(USFCreationClientObj,
                            UFSRequest.cast(UFSRequestObj));
                } catch (IllegalArgumentException iae) {
                    writeToErrorView(String.format(ILLEGAL_ARGS_EXE, creationClientMethod.getName()),
                            iae.getMessage(), ERROR_RESOLUTION, iae);
                } catch (InvocationTargetException ite) {
                    writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(), ERROR_RESOLUTION,
                            ite);
                }
                if (null != UFSResponseObj) {
                    outputViews.write(documentUtility.newDocument(processResponseObj(UFSResponseObj)));
                    counter.inc();
                }
            } else {
                writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION);
            }
        }
    } catch (Exception ex) {
        writeToErrorView(ERRORMSG, ex.getMessage(), ERROR_RESOLUTION, ex);
    }
}

From source file:org.tinymediamanager.scraper.moviemeternl.model.FilmDetail.java

public ArrayList getInner(XmlRpcArray arr, Class child) {
    ArrayList al = new ArrayList();

    for (int i = 0; i < arr.size(); i++) {
        XmlRpcStruct str = arr.getStruct(i);
        Constructor con;//from   w  w w.  j a v  a 2  s. c om
        Object object = null;
        try {
            con = child.getDeclaredConstructor(new Class[] { XmlRpcStruct.class });
            object = con.newInstance(new Object[] { str });
            al.add(object);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return al;
}

From source file:org.apache.ranger.authorization.hive.authorizer.RangerHiveMetastorePrivilegeHandler.java

public void init() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerHiveMetastorePrivilegHandler.init()");
    }//from  ww w  .  java2s .  c  o m

    try {

        rangerPluginClassLoader = RangerPluginClassLoader.getInstance(RANGER_PLUGIN_TYPE, this.getClass());

        @SuppressWarnings("unchecked")
        Class<MetaStoreEventListener> cls = (Class<MetaStoreEventListener>) Class
                .forName(RANGER_HIVE_METASTORE_AUTHORIZER_IMPL_CLASSNAME, true, rangerPluginClassLoader);

        activatePluginClassLoader();
        Constructor ctor = cls.getDeclaredConstructor(Configuration.class);
        rangerHiveMetastorePrivilegeHandlerImpl = (MetaStoreEventListener) ctor.newInstance(getConf());
    } catch (Exception e) {
        // check what need to be done
        LOG.error("Error Enabling RangerHdfsPluing", e);
    } finally {
        deactivatePluginClassLoader();
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerHdfsAuthorizer.init()");
    }
}

From source file:com.qualogy.qafe.business.resource.java.JavaClass.java

private Object createInstance(Class<?> clazz, JavaResource resource) {
    Object instance = null;/*w ww  .  jav a 2 s.  co  m*/
    try {
        //         List<Parameter> arguments = resource.getArguments();
        //         if(arguments!=null){
        //            Collections.sort(arguments);
        //            for (Parameter argument : arguments) {
        //               argument.get
        //            }
        //         }
        Constructor<?> constructor = clazz.getDeclaredConstructor(new Class[] {});
        constructor.setAccessible(true);
        instance = constructor.newInstance(new Object[] {});
    } catch (NoSuchMethodException e) {
        throw new ResourceInitializationException("possible error; no default constructor", e);
    } catch (InvocationTargetException e) {
        throw new ResourceInitializationException(e);
    } catch (IllegalAccessException e) {
        throw new ResourceInitializationException(e);
    } catch (InstantiationException e) {
        throw new ResourceInitializationException(e);
    }
    return instance;
}

From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java

/**
 * Support method./*from   www  . j  a v a  2s  .  c  o  m*/
 *
 * @param clz
 * @return
 */
private Object invokeInnerClassConstructor(Class<?> clz) {
    try {
        Constructor<?> noArgConstructor = clz.getDeclaredConstructor(SimpleAmqpMessageContainer.class);
        if (!noArgConstructor.isAccessible()) {
            noArgConstructor.setAccessible(true);
        }

        return noArgConstructor.newInstance(this);
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException
            | InvocationTargetException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}