Example usage for java.lang.reflect Method invoke

List of usage examples for java.lang.reflect Method invoke

Introduction

In this page you can find the example usage for java.lang.reflect Method invoke.

Prototype

@CallerSensitive
@ForceInline 
@HotSpotIntrinsicCandidate
public Object invoke(Object obj, Object... args)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException 

Source Link

Document

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

Usage

From source file:it.unibas.spicy.persistence.object.ClassUtility.java

public static void invokeSetMethod(String methodName, Object object, Object arg) {
    try {/*  ww w  .  ja  v  a2 s .  c  o  m*/
        Method[] methods = object.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                method.invoke(object, arg);
                return;
            }
        }
    } catch (Exception ex) {
        logger.error(ex);
    }
}

From source file:Main.java

public static Object isEmpty(Object obj, Class clazz) {
    if (obj == null || clazz == null) {
        return obj;
    }/*w w w .j  a  v  a2 s.co  m*/
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        try {
            String fieldName = field.getName();
            if (fieldName == null || fieldName.length() == 0)
                continue;
            String fieldMethodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            String getfieldName = "get" + fieldMethodName;
            Method getMethod = clazz.getMethod(getfieldName, null);
            if (getMethod == null)
                continue;
            Object value = getMethod.invoke(obj, null);
            Class type = field.getType();
            if (type == String.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().trim().length() == 0) {
                    value = "";
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, String.class);
                    if (setMethod == null)
                        continue;
                    setMethod.invoke(obj, value);
                }
            } else if (type == Integer.class || type == int.class || type == Float.class || type == float.class
                    || type == Double.class || type == double.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().length() == 0) {
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, type);
                    setMethod.invoke(obj, 0);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
    return obj;
}

From source file:Main.java

public static Object invokeMethod(Object handler, String callback, Class<?>[] cls, Object... params) {

    if (handler == null || callback == null)
        return null;

    Method method = null;

    try {/*from   w  w  w.  j  a  v a2 s .  co m*/
        if (cls == null)
            cls = new Class[0];
        method = handler.getClass().getMethod(callback, cls);
        return method.invoke(handler, params);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    return null;

}

From source file:com.maomao.framework.utils.ReflectUtils.java

/**
 * ?/*from   w w  w .ja va  2 s.  com*/
 * @param obj
 * @param methodName
 * @param clazz
 * @param params
 * @return
 * @throws Exception
 */
public static Object invok(Object obj, String methodName, Class<?>[] clazz, Object[] params) throws Exception {
    Method method = obj.getClass().getMethod(methodName, clazz);
    return method.invoke(obj, params);
}

From source file:com.rockagen.commons.util.SysUtil.java

/**
 * *//from www  . jav  a  2  s.co m
 *
 * @param url url
 * @throws Exception exception if occur
 */
public static void browse(String url) throws Exception {
    if (OS_NAME.startsWith("Mac OS")) {
        Method openURL = ClassUtil.getDeclaredMethod(Class.forName("com.apple.eio.FileManager"), true,
                "openURL", String.class);
        openURL.invoke(null, url);

    } else if (OS_NAME.startsWith("Windows")) {

        Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
    } else {
        // assume Unix or Linux
        String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };
        String browser = null;
        for (int count = 0; count < browsers.length && browser == null; count++)
            if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)
                browser = browsers[count];
        if (browser == null)
            throw new NoSuchMethodException("Could not find web browser");
        else
            Runtime.getRuntime().exec(new String[] { browser, url });
    }
}

From source file:Main.java

public static File getExternalDownload() {
    try {//  w ww  .ja v a2 s . c om
        Class<?> c = Class.forName("android.os.Environment");
        Method m = c.getDeclaredMethod("getExternalStoragePublicDirectory", String.class);
        String download = c.getDeclaredField("DIRECTORY_DOWNLOADS").get(null).toString();
        return (File) m.invoke(null, download);
    } catch (Exception e) {
        return new File(Environment.getExternalStorageDirectory(), "Download");
    }
}

From source file:Main.java

public static Object toSerializableObject(Object obj) {
    // Case for objects have no specified method to JSON string.
    if (obj.getClass().isArray()) {
        JSONArray result = new JSONArray();
        Object[] arr = (Object[]) obj;
        for (int i = 0; i < arr.length; ++i) {
            try {
                result.put(i, toSerializableObject(arr[i]));
            } catch (Exception e) {
                e.printStackTrace();//from ww  w. j  a  va2 s.  c o m
            }
        }
        return result;
    }
    // The original serializable object.
    if (isSerializable(obj))
        return obj;

    // Customized serializable object.
    //
    // If the object is not directly serializable, we check if it is customised
    // serializable. That means the developer implemented the public serialization
    // method "toJSONString".
    try {
        Method m = obj.getClass().getMethod("toJSONString", new Class<?>[0]);
        String jsonStr = (String) (m.invoke(obj, new Object[0]));
        if (jsonStr.trim().charAt(0) == '[') {
            return new JSONArray(jsonStr);
        } else {
            return new JSONObject(jsonStr);
        }
    } catch (Exception e) {
        Log.w(TAG, "No serialization method: \"toJSONString\", or errors happened.");
    }

    /*
     * For ordinary objects, we will just serialize the accessible fields.
     */
    try {
        Class<?> c = obj.getClass();
        JSONObject json = new JSONObject();
        Field[] fields = c.getFields();
        for (Field f : fields) {
            json.put(f.getName(), f.get(obj));
        }
        return json;
    } catch (Exception e) {
        Log.e(TAG, "Field to serialize object to JSON.");
        e.printStackTrace();
        return null;
    }
}

From source file:com.networknt.audit.ServerInfoDisabledTest.java

static void addURL(URL url) throws Exception {
    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class clazz = URLClassLoader.class;
    // Use reflection
    Method method = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);//from  w  ww .jav  a  2  s .  co  m
    method.invoke(classLoader, new Object[] { url });
}

From source file:Main.java

/**
 * Computes the center point of the current screen device. If this method is called on JDK 1.4, Xinerama-aware
 * results are returned. (See Sun-Bug-ID 4463949 for details).
 *
 * @return the center point of the current screen.
 *//*from  w  w w . j a v  a2s  . com*/
public static Point getCenterPoint() {
    final GraphicsEnvironment localGraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    try {
        final Method method = GraphicsEnvironment.class.getMethod("getCenterPoint", (Class[]) null);
        return (Point) method.invoke(localGraphicsEnvironment, (Object[]) null);
    } catch (Exception e) {
        // ignore ... will fail if this is not a JDK 1.4 ..
    }

    final Dimension s = Toolkit.getDefaultToolkit().getScreenSize();
    return new Point(s.width / 2, s.height / 2);
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static String getDeviceSerial() {
    String serial = "null";
    try {/*ww  w . j  av a  2 s .com*/
        Class clazz = Class.forName("android.os.Build");
        Class paraTypes = Class.forName("java.lang.String");
        Method method = clazz.getDeclaredMethod("getString", paraTypes);
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        serial = (String) method.invoke(new Build(), "ro.serialno");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return serial;
}