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:AWTUtilities.java

/**
 * Returns a list of available font names. Under JDK1.1 it uses
 * <code>Toolkit.getFontList()</code> while under JDK1.2 (via reflection),
 * <code>GraphicsEnvironment.getAvailableFontFamilyNames()</code>
 *//*from  ww  w . j  ava2 s.  c  o m*/

public static String[] getAvailableFontNames() {
    if (PlatformUtils.isJavaBetterThan("1.2")) {
        try {
            // The equivalent of "return GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();"
            Class geClass = Class.forName("java.awt.GraphicsEnvironment");
            Method getLocalGraphicsEnvironmentMethod = geClass.getMethod("getLocalGraphicsEnvironment",
                    new Class[0]);
            Object localGE = getLocalGraphicsEnvironmentMethod.invoke(null, new Object[0]);
            Method getAvailableFontFamilyNamesMethod = geClass.getMethod("getAvailableFontFamilyNames",
                    new Class[0]);
            String[] fontNames = (String[]) getAvailableFontFamilyNamesMethod.invoke(localGE, new Object[0]);
            return fontNames;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    } else
        return Toolkit.getDefaultToolkit().getFontList();
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static Method getSetMethod(Class objectClass, String fieldName) {

    try {/* w  w w . ja  v a 2 s . co  m*/

        Class[] parameterTypes = new Class[1];

        Field field = objectClass.getDeclaredField(fieldName);

        parameterTypes[0] = field.getType();

        StringBuffer sb = new StringBuffer();

        sb.append("set");

        sb.append(fieldName.substring(0, 1).toUpperCase());

        sb.append(fieldName.substring(1));

        Method method = objectClass.getMethod(sb.toString(), parameterTypes);

        return method;

    } catch (Exception e) {

        e.printStackTrace();

    }

    return null;

}

From source file:com.ery.estorm.util.ReflectionUtils.java

/**
 * This code is to support backward compatibility and break the compile time dependency of core on mapred. This should be made
 * deprecated along with the mapred package HADOOP-1230. Should be removed when mapred package is removed.
 */// w w  w .  j a va 2  s  . c om
private static void setJobConf(Object theObject, Configuration conf) {
    // If JobConf and JobConfigurable are in classpath, AND
    // theObject is of type JobConfigurable AND
    // conf is of type JobConf then
    // invoke configure on theObject
    try {
        Class<?> jobConfClass = conf.getClassByName("org.apache.hadoop.mapred.JobConf");
        Class<?> jobConfigurableClass = conf.getClassByName("org.apache.hadoop.mapred.JobConfigurable");
        if (jobConfClass.isAssignableFrom(conf.getClass())
                && jobConfigurableClass.isAssignableFrom(theObject.getClass())) {
            Method configureMethod = jobConfigurableClass.getMethod("configure", jobConfClass);
            configureMethod.invoke(theObject, conf);
        }
    } catch (ClassNotFoundException e) {
        // JobConf/JobConfigurable not in classpath. no need to configure
    } catch (Exception e) {
        throw new RuntimeException("Error in configuring object", e);
    }
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Finds a method./* ww w . jav a  2  s  .c om*/
 *
 * @param clazz the clazz
 * @param name the name
 * @param argumentTypes the argument types
 * @return null if not found.
 */
public static Method findMethod(Class<?> clazz, String name, Class<?>... argumentTypes) {
    try {
        return clazz.getMethod(name, argumentTypes);
    } catch (SecurityException | NoSuchMethodException e) {
        return null;
    }
}

From source file:kina.utils.Utils.java

/**
 * Resolves the setter name for the property whose name is 'propertyName' whose type is 'valueType'
 * in the entity bean whose class is 'entityClass'.
 * If we don't find a setter following Java's naming conventions, before throwing an exception we try to
 * resolve the setter following Scala's naming conventions.
 *
 * @param propertyName the field name of the property whose setter we want to resolve.
 * @param entityClass  the bean class object in which we want to search for the setter.
 * @param valueType    the class type of the object that we want to pass to the setter.
 * @return the resolved setter.//from   ww  w  .  jav a 2  s.  c  o m
 */
@SuppressWarnings("unchecked")
public static Method findSetter(String propertyName, Class entityClass, Class valueType) {
    Method setter;

    String setterName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);

    try {
        setter = entityClass.getMethod(setterName, valueType);
    } catch (NoSuchMethodException e) {
        // let's try with scala setter name
        try {
            setter = entityClass.getMethod(propertyName + "_$eq", valueType);
        } catch (NoSuchMethodException e1) {
            throw new IOException(e1);
        }
    }

    return setter;
}

From source file:com.microsoft.tfs.client.common.ui.framework.helper.ColorUtils.java

/**
 * Gets the windows system color identified by id (deferring to GetSysColor
 * system call.)/*www  . j av a  2  s.  c  o m*/
 *
 * This color MUST NOT be disposed.
 *
 * @param colorName
 *        The id of the color to be resolved.
 * @throws IllegalArgumentException
 *         if the current platform is not win32
 * @return The color identified by this id, or null if it could not be
 *         looked up.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Color getWin32SystemColor(final Display display, final int colorId) {
    Check.isTrue(WindowSystem.isCurrentWindowSystem(WindowSystem.WIN32), "WindowSystem.WIN32"); //$NON-NLS-1$

    try {
        final Class colorClass = Class.forName("org.eclipse.swt.graphics.Color"); //$NON-NLS-1$

        if (colorClass == null) {
            log.warn("Could not load win32 color class"); //$NON-NLS-1$
        } else {
            final Method createMethod = colorClass.getMethod("win32_new", new Class[] { //$NON-NLS-1$
                    Device.class, int.class });

            if (createMethod == null) {
                log.warn("Could not load win32 new color method"); //$NON-NLS-1$
            } else {
                final Object color = createMethod.invoke(colorClass, new Object[] { display, colorId });

                if (color == null) {
                    log.warn(MessageFormat.format("Could not query win32 color id {0}", //$NON-NLS-1$
                            Integer.toString(colorId)));
                } else if (!(color instanceof Color)) {
                    log.warn("Received non-color from win32 color query"); //$NON-NLS-1$
                } else {
                    return (Color) color;
                }
            }
        }
    } catch (final Throwable t) {
        log.warn("Could not load win32 color", t); //$NON-NLS-1$
    }

    return null;
}

From source file:com.aurel.track.persist.ReflectionHelper.java

/**
 * This method replaces all occurrences of <code>ProjectType</code> 
 * value oldOID with project type value newOID going through all related
 * tables in the database.//  ww w .  j ava  2 s .  c o  m
 * @param oldOID object identifier of list type to be replaced
 * @param newOID object identifier of replacement list type
 */
public static void delete(Class[] peerClasses, String[] fields, Integer oldOID) {
    // Do this using reflection.      
    Criteria selectCriteria = new Criteria();
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        selectCriteria.clear();
        selectCriteria.add(field, oldOID, Criteria.EQUAL);
        try {
            Class partypes[] = new Class[1];
            partypes[0] = Criteria.class;
            Method meth = peerClass.getMethod("doDelete", partypes);
            Object arglist[] = new Object[1];
            arglist[0] = selectCriteria;
            meth.invoke(peerClass, arglist);
        } catch (Exception e) {
            LOGGER.error("Exception when trying to delete dependent data for oldOID " + oldOID + " class "
                    + peerClass.toString() + " and field " + field + ": " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:main.java.stroum.vkapp.VK.LongPoll.java

private static void processEvent(JSONArray array, String className) {
    for (int i = 0; i < array.length(); ++i) {
        try {/* w  w  w  .  j  a v  a 2 s.  c om*/
            JSONArray arrayItem = (JSONArray) array.get(i);
            int type = (Integer) arrayItem.get(0);
            int uid;

            /*
            0,$message_id,0 --  ?? ?  local_id
            1,$message_id,$flags --   ?? (FLAGS:=$flags)
            2,$message_id,$mask[,$user_id] -- ?  ?? (FLAGS|=$mask)
            3,$message_id,$mask[,$user_id] -- ??  ?? (FLAGS&=~$mask)
            4,$message_id,$flags,$from_id,$timestamp,$subject,$text,$attachments --   ??
            8,-$user_id,0 --  $user_id ? 
            9,-$user_id,$flags --  $user_id ?  ($flags  0, ?   ? (,  )  1, ?    (, ?? away))
                    
                    
            51,$chat_id,$self --    (??, ) ? $chat_id  . $self -   ?  ? 
            61,$user_id,$flags --  $user_id   ?  . ?     ~5 ?  ??  ?. $flags = 1
            62,$user_id,$chat_id --  $user_id   ?  ? $chat_id.
            70,$user_id,$call_id --  $user_id ?    $call_id,       ??  voip.getCallInfo.
            */

            switch (type) {
            case 8:
                // uid = Math.abs(Integer.parseInt(arrayItem.get(1).toString()));
                // System.out.println(VK.getUserName(uid) + " is online");
                break;
            case 9:
                // uid = Math.abs(Integer.parseInt(arrayItem.get(1).toString()));
                //System.out.println(VK.getUserName(uid) + " is offline");
                break;
            case 4:
                Long message_id = Long.parseLong(arrayItem.get(1).toString());
                int flags = Integer.parseInt(arrayItem.get(2).toString());
                int from_id = Integer.parseInt(arrayItem.get(3).toString());
                Long ts = Long.parseLong(arrayItem.get(4).toString());
                String subject = arrayItem.get(5).toString();
                String text = arrayItem.get(6).toString();
                int from_uid = 0;
                try {
                    JSONObject object = new JSONObject(arrayItem.get(7).toString());
                    from_uid = Integer.parseInt(object.getString("from"));
                } catch (Exception ignored) {
                }

                try {
                    Class c = Class.forName("main.java.stroum.vkapp.Handlers." + className); // Todo: Fix
                    Class[] paramTypes = new Class[] { Message.class };
                    Object[] args = new Object[] {
                            new Message(message_id, flags, from_id, ts, text, from_uid) };
                    Method m = c.getMethod("handleMessage", paramTypes);
                    m.invoke(c, args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }

        } catch (JSONException ignored) {
        }
    }
}

From source file:com.aurel.track.persist.ReflectionHelper.java

/**
 * This method replaces all occurrences of <code>ProjectType</code> 
 * value oldOID with project type value newOID going through all related
 * tables in the database./* w w w  .  jav a2 s. c o m*/
 * @param oldOID object identifier of list type to be replaced
 * @param newOID object identifier of replacement list type
 */
public static boolean hasDependentData(Class[] peerClasses, String[] fields, Integer oldOID) {
    // Do this using reflection.
    Criteria selectCriteria = new Criteria();
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        selectCriteria.clear();
        selectCriteria.add(field, oldOID, Criteria.EQUAL);
        try {
            Class partypes[] = new Class[1];
            partypes[0] = Criteria.class;
            Method meth = peerClass.getMethod("doSelect", partypes);

            Object arglist[] = new Object[1];
            arglist[0] = selectCriteria;
            List results = (List) meth.invoke(peerClass, arglist);
            if (results != null && !results.isEmpty()) {
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("Exception when trying to find dependent data for " + "oldOID " + oldOID
                    + " for class " + peerClass.toString() + " and field " + field + ": " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return false;
}

From source file:com.varaneckas.hawkscope.util.OSUtils.java

/**
* Gets the tray icon size//from   w  w  w. j a  v a 2s .c o m
* 
* @return
*/
public static int getTrayIconSize() {
    //experimental
    if (System.getProperty("java.version").compareTo("1.6") >= 0) {
        try {
            log.debug("Java > 1.6, trying java.awt.SystemTray");
            final Class<?> systemTrayClass = Class.forName("java.awt.SystemTray");
            Method m = systemTrayClass.getMethod("getSystemTray", new Class[] {});
            final Object systemTray = m.invoke(systemTrayClass, new Object[] {});
            m = systemTray.getClass().getMethod("getTrayIconSize", new Class[] {});
            final Object size = m.invoke(systemTray, new Object[] {});
            m = null;
            return ((java.awt.Dimension) size).height;
        } catch (final Exception e) {
            log.warn("Failed calling java.awt.SystemTray object", e);
        }
    }
    if (CURRENT_OS.equals(OS.WIN)) {
        return 16;
    }
    if (CURRENT_OS.equals(OS.UNIX)) {
        return 24;
    }
    if (CURRENT_OS.equals(OS.MAC)) {
        return 16;
    }
    return 16;
}