Example usage for java.lang Class getConstructor

List of usage examples for java.lang Class getConstructor

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:eu.unifiedviews.plugins.extractor.filesdownload.ReflectionSocketFactory.java

/**
 * This method attempts to execute Socket method available since Java 1.4
 * using reflection. If the methods are not available or could not be executed <tt>null</tt> is returned
 * /*from   www  .  ja v a  2 s  .  c om*/
 * @param socketfactoryName
 *            name of the socket factory class
 * @param host
 *            the host name/IP
 * @param port
 *            the port on the host
 * @param localAddress
 *            the local host name/IP to bind the socket to
 * @param localPort
 *            the port on the local machine
 * @param timeout
 *            the timeout value to be used in milliseconds. If the socket cannot be
 *            completed within the given time limit, it will be abandoned
 * @return a connected Socket
 * @throws IOException
 *             if an I/O error occurs while creating the socket
 * @throws UnknownHostException
 *             if the IP address of the host cannot be
 *             determined
 * @throws ConnectTimeoutException
 *             if socket cannot be connected within the
 *             given time limit
 */
public static Socket createSocket(final Object socketfactory, final String host, final int port,
        final InetAddress localAddress, final int localPort, int timeout)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (REFLECTION_FAILED) {
        //This is known to have failed before. Do not try it again
        return null;
    }
    // This code uses reflection to essentially do the following:
    //
    //  SocketFactory socketFactory = Class.forName(socketfactoryName).getDefault();
    //  Socket socket = socketFactory.createSocket();
    //  SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    //  SocketAddress remoteaddr = new InetSocketAddress(host, port);
    //  socket.bind(localaddr);
    //  socket.connect(remoteaddr, timeout);
    //  return socket;
    try {
        Class socketfactoryClass = socketfactory.getClass();//Class.forName(socketfactoryName);
        Method method = socketfactoryClass.getMethod("getDefault", new Class[] {});
        //            Object socketfactory = method.invoke(null, 
        //                new Object[] {});
        method = socketfactoryClass.getMethod("createSocket", new Class[] {});
        Socket socket = (Socket) method.invoke(socketfactory, new Object[] {});

        if (INETSOCKETADDRESS_CONSTRUCTOR == null) {
            Class addressClass = Class.forName("java.net.InetSocketAddress");
            INETSOCKETADDRESS_CONSTRUCTOR = addressClass
                    .getConstructor(new Class[] { InetAddress.class, Integer.TYPE });
        }

        Object remoteaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { InetAddress.getByName(host), new Integer(port) });

        Object localaddr = INETSOCKETADDRESS_CONSTRUCTOR
                .newInstance(new Object[] { localAddress, new Integer(localPort) });

        if (SOCKETCONNECT_METHOD == null) {
            SOCKETCONNECT_METHOD = Socket.class.getMethod("connect",
                    new Class[] { Class.forName("java.net.SocketAddress"), Integer.TYPE });
        }

        if (SOCKETBIND_METHOD == null) {
            SOCKETBIND_METHOD = Socket.class.getMethod("bind",
                    new Class[] { Class.forName("java.net.SocketAddress") });
        }
        SOCKETBIND_METHOD.invoke(socket, new Object[] { localaddr });
        SOCKETCONNECT_METHOD.invoke(socket, new Object[] { remoteaddr, new Integer(timeout) });
        return socket;
    } catch (InvocationTargetException e) {
        Throwable cause = e.getTargetException();
        if (SOCKETTIMEOUTEXCEPTION_CLASS == null) {
            try {
                SOCKETTIMEOUTEXCEPTION_CLASS = Class.forName("java.net.SocketTimeoutException");
            } catch (ClassNotFoundException ex) {
                // At this point this should never happen. Really.
                REFLECTION_FAILED = true;
                return null;
            }
        }
        if (SOCKETTIMEOUTEXCEPTION_CLASS.isInstance(cause)) {
            throw new ConnectTimeoutException(
                    "The host did not accept the connection within timeout of " + timeout + " ms", cause);
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        return null;
    } catch (Exception e) {
        REFLECTION_FAILED = true;
        return null;
    }
}

From source file:com.qwazr.utils.ExceptionUtils.java

@SuppressWarnings("unchecked")
public static <T extends Exception> T throwException(Exception exception, Class<T> exceptionClass) throws T {
    if (exception == null)
        return null;
    if (exceptionClass.isInstance(exception))
        throw (T) exception;
    try {//www .j  a  v  a2s  .  co m
        return exceptionClass.getConstructor(Exception.class).newInstance(exception);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.chiorichan.factory.groovy.GroovyRegistry.java

public static Script getCachedScript(ScriptingContext context, Binding binding) {
    try {//from  w w  w . j a v a 2s .co  m
        // File classFile = FileFunc.buildFile( context.cache(), context.scriptPackage().replace( '.', File.separatorChar ), context.scriptSimpleName() + ".class" );
        if (scriptCacheMd5.containsKey(context.scriptClassName())) {
            if (scriptCacheMd5.get(context.site().getId() + "//" + context.scriptClassName())
                    .equals(context.md5())) {
                Class<?> scriptClass = Class.forName(context.scriptClassName());
                Constructor<?> con = scriptClass.getConstructor(Binding.class);
                Script script = (Script) con.newInstance(binding);
                return script;
            }
        } else
            scriptCacheMd5.put(context.site().getId() + "//" + context.scriptClassName(), context.md5());
    } catch (Throwable t) {

    }
    return null;
}

From source file:com.google.code.pentahoflashcharts.charts.PentahoOFC4JChartHelper.java

@SuppressWarnings("unchecked")
public static String generateChartJson(Node chartNode, IPentahoResultSet data, boolean byRow, Log log) {
    String chartType = null;/*ww  w.ja  va  2s.co m*/
    String factoryClassString = null;
    try {
        Node temp = chartNode.selectSingleNode(CHART_TYPE_NODE_LOC);
        if (AbstractChartFactory.getValue(temp) != null) {
            chartType = AbstractChartFactory.getValue(temp);
        } else {
            // This should NEVER happen.
            chartType = CHART_TYPE_DEFAULT;
        }

        factoryClassString = (String) getChartFactories().get(chartType);
        if (factoryClassString == null) {
            throw new RuntimeException(Messages.getErrorString(
                    "PentahoOFC4JChartHelper.ERROR_0001_FACTORY_INIT", chartType, factoryClassString)); //$NON-NLS-1$
        } else {

            Class factoryClass = Class.forName(factoryClassString);

            // throw exception if factoryClass not found

            IChartFactory factory = (IChartFactory) factoryClass.getConstructor(new Class[0])
                    .newInstance(new Object[0]);
            factory.setChartNode(chartNode);
            factory.setLog(log);
            if (byRow) {
                factory.setData(PentahoDataTransmuter.pivot(data));
            } else {
                factory.setData(data);
            }
            return factory.convertToJson();
        }
    } catch (Exception e) {
        logger.error(Messages.getErrorString("PentahoOFC4JChartHelper.ERROR_0001_FACTORY_INIT", chartType, //$NON-NLS-1$
                factoryClassString), e);
        throw new RuntimeException(e);
    }
}

From source file:org.eel.kitchen.jsonschema.keyword.KeywordFactory.java

/**
 * Build one validator/*w w w . ja v  a2 s  . c om*/
 *
 * <p>This is done by reflection. Remember that the contract is to have a
 * constructor which takes a {@link JsonNode} as an argument.
 * </p>
 *
 * <p>If instantiation fails for whatever reason, an "invalid validator" is
 * returned which always fails.</p>
 *
 * @see #invalidValidator(Class, Exception)
 *
 * @param c the keyword validator class
 * @param schema the schema
 * @return the instantiated keyword validator
 */
private static KeywordValidator buildValidator(final Class<? extends KeywordValidator> c,
        final JsonNode schema) {
    final Constructor<? extends KeywordValidator> constructor;

    try {
        constructor = c.getConstructor(JsonNode.class);
    } catch (NoSuchMethodException e) {
        return invalidValidator(c, e);
    }

    try {
        return constructor.newInstance(schema);
    } catch (InstantiationException e) {
        return invalidValidator(c, e);
    } catch (IllegalAccessException e) {
        return invalidValidator(c, e);
    } catch (InvocationTargetException e) {
        return invalidValidator(c, e);
    }
}

From source file:com.agimatec.validation.jsr303.util.SecureActions.java

public static <T> Constructor<T> getConstructor(final Class<T> clazz, final Class<?>... params) {
    return run(new PrivilegedAction<Constructor<T>>() {
        public Constructor<T> run() {
            try {
                return clazz.getConstructor(params);
            } catch (NoSuchMethodException e) {
                return null;
            }/*  www .j ava 2  s  . c  om*/
        }
    });
}

From source file:com.myee.tarot.core.exception.ExceptionHelper.java

private static <J extends RuntimeException> RuntimeException wrapException(Throwable e, Class<J> wrapType,
        String message) {//w ww  .ja  v a2s. c o m
    if (e instanceof RuntimeException) {
        return (RuntimeException) e;
    }
    try {
        if (StringUtils.isEmpty(message)) {
            return wrapType.getConstructor(Throwable.class).newInstance(e);
        } else {
            return wrapType.getConstructor(String.class, Throwable.class).newInstance(message, e);
        }
    } catch (Exception e1) {
        LOG.error("Could not wrap exception", e1);
        throw new RuntimeException(e);
    }
}

From source file:com.ancientprogramming.fixedformat4j.format.FixedFormatUtil.java

public static <T> FixedFormatter<T> getFixedFormatterInstance(Class<? extends FixedFormatter<T>> formatterClass,
        Class paramType, FormatContext paramValue) {
    FixedFormatter<T> result;/*from   w ww  . ja v  a 2s  .co m*/
    if (paramType != null && paramValue != null) {
        try {
            result = formatterClass.getConstructor(paramType).newInstance(paramValue);
        } catch (NoSuchMethodException e) {
            result = null;
        } catch (Exception e) {
            throw new FixedFormatException("Could not create instance with one argument constructor", e);
        }
    } else {
        try {
            result = formatterClass.getConstructor().newInstance();
        } catch (NoSuchMethodException e) {
            result = null;
        } catch (Exception e) {
            throw new FixedFormatException("Could not create instance with no arg constructor", e);
        }
    }
    return result;
}

From source file:com.alibaba.wasp.client.ServerCallable.java

private static RuntimeException unwrapRuntimeException(Throwable t) {
    if (StringUtils.isNotEmpty(t.getMessage())) {
        try {//from  ww  w.j av  a  2s .  c  o  m
            Class exceptionClass = Class.forName(t.getMessage());
            Constructor cn = exceptionClass.getConstructor(String.class);
            cn.setAccessible(true);
            String firstLine = t.getMessage();

            Object ex = cn.newInstance(firstLine);
            if (ex instanceof RuntimeException) {
                return (RuntimeException) ex;
            }
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (InstantiationException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
    }
    return null;
}

From source file:corner.orm.gae.GaeModule.java

public static Delegate buildDelegate(@Builtin ClassFactory classFactory) throws Throwable {
    String className = "com.google.appengine.tools.development.ApiProxyLocalImpl";
    ClassFab classFab = classFactory.newClass("MyApiLocalEnvir", Class.forName(className));
    classFab.addConstructor(new Class[] { File.class }, new Class[] {}, "super($1);");
    Class clazz = classFab.createClass();
    return (Delegate) clazz.getConstructor(File.class).newInstance(new File("target"));
}