Example usage for java.lang Class getMethod

List of usage examples for java.lang Class getMethod

Introduction

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

Prototype

@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Usage

From source file:com.he5ed.lib.cloudprovider.utils.AuthHelper.java

/**
 * Get parameters to be passed to Volley request to get access token
 *
 * @param cloudApi type of cloud account
 * @param authCode code from authorization process
 * @return Map//w w w  .  ja va 2  s  . c  o  m
 */
public static RequestBody getAccessTokenBody(String cloudApi, String authCode) {
    // use reflection for flexibility
    try {
        Class<?> clazz = Class.forName(cloudApi);
        Method getAccessTokenBody = clazz.getMethod("getAccessTokenBody", String.class);
        return (RequestBody) getAccessTokenBody.invoke(null, authCode);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.he5ed.lib.cloudprovider.utils.AuthHelper.java

/**
 * Create OkHttp request to get user information
 *
 * @param cloudApi type of cloud account
 * @param accessToken access token for authorization
 * @return Request//from  w ww .  j a v a  2 s .com
 */
public static Request getUserInfoRequest(String cloudApi, String accessToken) {
    // use reflection for flexibility
    try {
        Class<?> clazz = Class.forName(cloudApi);
        Method getUserInfoRequest = clazz.getMethod("getUserInfoRequest", String.class);
        return (Request) getUserInfoRequest.invoke(null, accessToken);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.he5ed.lib.cloudprovider.utils.AuthHelper.java

/**
 * Extract access token from the JSONObject
 *
 * @param cloudApi type of cloud account
 * @param jsonObject JSONObject that contain access token
 * @return Map/* w  w w .j ava2s .  c o  m*/
 * @throws JSONException
 */
public static Map<String, String> extractAccessToken(String cloudApi, JSONObject jsonObject)
        throws JSONException {
    // use reflection for flexibility
    try {
        Class<?> clazz = Class.forName(cloudApi);
        Method extractAccessToken = clazz.getMethod("extractAccessToken", JSONObject.class);
        return (Map) extractAccessToken.invoke(null, jsonObject);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        // catch exception throw by class method
        if (e.getCause() instanceof JSONException) {
            throw new JSONException(e.getMessage());
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:Main.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Method getMethod(Class clazz, String methodName, final Class[] classes) throws Exception {
    Method method = null;/* w  w  w .ja v a  2  s .c  o  m*/
    try {
        method = clazz.getDeclaredMethod(methodName, classes);
    } catch (NoSuchMethodException e) {
        try {
            method = clazz.getMethod(methodName, classes);
        } catch (NoSuchMethodException ex) {
            if (clazz.getSuperclass() == null) {
                return method;
            } else {
                method = getMethod(clazz.getSuperclass(), methodName, classes);
            }
        }
    }
    return method;
}

From source file:org.lambdamatic.internal.elasticsearch.codec.DocumentCodec.java

/**
 * Attempts to look-up a {@code valueOf(String)} or {@code parse(CharSequence)} method in the
 * given {@code targetType} to allow for value setting with a conversion.
 * //  w ww .j a v  a  2s. c o  m
 * @param targetType the type in which the convert method must be looked-up
 * @return the method to apply, or <code>null</code> if none was found.
 */
private static Method getConvertMethod(final Class<?> targetType) {
    try {
        return targetType.getMethod("valueOf", String.class);
    } catch (NoSuchMethodException | SecurityException e) {
        // ignore, the method just does not exist.
    }
    try {
        return targetType.getMethod("parse", CharSequence.class);
    } catch (NoSuchMethodException | SecurityException e) {
        // ignore, the method just does not exist.
    }
    return null;
}

From source file:de.alpharogroup.lang.object.CloneObjectExtensions.java

/**
 * Try to clone the given object.//  w w  w.j a  v a  2  s.  c  om
 *
 * @param object
 *            The object to clone.
 * @return The cloned object or null if the clone process failed.
 * @throws NoSuchMethodException
 *             Thrown if a matching method is not found or if the name is "&lt;init&gt;"or
 *             "&lt;clinit&gt;".
 * @throws SecurityException
 *             Thrown if the security manager indicates a security violation.
 * @throws IllegalAccessException
 *             Thrown if this {@code Method} object is enforcing Java language access control
 *             and the underlying method is inaccessible.
 * @throws IllegalArgumentException
 *             Thrown if an illegal argument is given
 * @throws InvocationTargetException
 *             Thrown if the property accessor method throws an exception
 * @throws ClassNotFoundException
 *             occurs if a given class cannot be located by the specified class loader
 * @throws InstantiationException
 *             Thrown if one of the following reasons: the class object
 *             <ul>
 *             <li>represents an abstract class</li>
 *             <li>represents an interface</li>
 *             <li>represents an array class</li>
 *             <li>represents a primitive type</li>
 *             <li>represents {@code void}</li>
 *             <li>has no nullary constructor</li>
 *             </ul>
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Object cloneObject(final Object object)
        throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException, ClassNotFoundException, InstantiationException, IOException {
    Object clone = null;
    // Try to clone the object if it implements Serializable.
    if (object instanceof Serializable) {
        clone = SerializedObjectExtensions.copySerializedObject((Serializable) object);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object if it is Cloneble.
    if (clone == null && object instanceof Cloneable) {

        if (object.getClass().isArray()) {
            final Class<?> componentType = object.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                int length = Array.getLength(object);
                clone = Array.newInstance(componentType, length);
                while (length-- > 0) {
                    Array.set(clone, length, Array.get(object, length));
                }
            } else {
                clone = ((Object[]) object).clone();
            }
            if (clone != null) {
                return clone;
            }
        }
        final Class<?> clazz = object.getClass();
        final Method cloneMethod = clazz.getMethod("clone", (Class[]) null);
        clone = cloneMethod.invoke(object, (Object[]) null);
        if (clone != null) {
            return clone;
        }
    }
    // Try to clone the object by copying all his properties with
    // the BeanUtils.copyProperties() method.
    if (clone == null) {
        clone = ReflectionExtensions.getNewInstance(object);
        BeanUtils.copyProperties(clone, object);
    }
    return clone;
}

From source file:Main.java

public static void chmod(String filename, int permissions) {
    Class<?> fileUtils = null;
    try {/*from  w  ww  .jav  a2 s .com*/
        fileUtils = Class.forName("android.os.FileUtils");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    Method setPermissions = null;
    int a;
    try {
        setPermissions = fileUtils.getMethod("setPermissions",
                new Class[] { String.class, int.class, int.class, int.class });
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    try {
        a = (Integer) setPermissions.invoke(null, filename, permissions, -1, -1);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Sets the vm policy./*from  www .  ja  va2  s.  co m*/
 *
 * @param strictMode
 *            the strict mode to work with
 * @throws ClassNotFoundException
 *             on problem
 * @throws NoSuchMethodException
 *             on problem
 * @throws InstantiationException
 *             on problem
 * @throws IllegalAccessException
 *             on problem
 * @throws InvocationTargetException
 *             on problem
 */
private static void setVmPolicy(final Class<?> strictMode) throws ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException {
    Class<?> vmPolicyType = Class.forName("android.os.StrictMode$VmPolicy");
    Method setVmPolicy = strictMode.getMethod("setVmPolicy", vmPolicyType);
    Class<?> vmPolicyBuilder = Class.forName("android.os.StrictMode$VmPolicy$Builder");

    Object policy = buildPolicy(vmPolicyBuilder);
    setVmPolicy.invoke(strictMode, policy);
}

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 w ww  .  j a v  a  2  s . co m*/
 * @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:jp.rikinet.util.dto.DtoFactory.java

/**
 * ?? DTO ??//www  . j  av a2s  .c o m
 * @param dto ??? DTO
 * @param name ??birthDate ? setter ? setBirthDate()
 * @param value ?
 */
private static void setProperty(Root dto, String name, Object value) {
    Class<?> cl = dto.getClass();
    String mName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
    try {
        Method m = cl.getMethod(mName, value.getClass());
        m.invoke(dto, value);
    } catch (NoSuchMethodException e) {
        throw new IllegalArgumentException("setter not found", e);
    } catch (InvocationTargetException | IllegalAccessException e) {
        throw new IllegalArgumentException("setter call failed", e);
    }
}