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.bosscs.spark.commons.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  w w  w .  j av a2 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 HadoopIOException(e1);
        }
    }

    return setter;
}

From source file:com.stratio.deep.commons.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.// w w  w.j  a  va  2  s  . co 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 DeepIOException(e1);
        }
    }

    return setter;
}

From source file:AWTUtilities.java

/**
 * Attempts to determine the usable screen bounds of the default screen
 * device. If the require java.awt API is not available under the JVM we're
 * running in, this will simply return the screen bounds obtained via
 * <code>Toolkit.getScreenSize()</code>.
 *//*w w  w  .j a  v  a2 s.  c o  m*/

public static Rectangle getUsableScreenBounds() {
    if (PlatformUtils.isJavaBetterThan("1.4")) {
        try {
            Class graphicsEnvironmentClass = Class.forName("java.awt.GraphicsEnvironment");
            Class graphicsDeviceClass = Class.forName("java.awt.GraphicsDevice");
            Class graphicsConfigurationClass = Class.forName("java.awt.GraphicsConfiguration");

            Class[] emptyClassArr = new Class[0];
            Method getLocalGraphicsEnvironmentMethod = graphicsEnvironmentClass
                    .getMethod("getLocalGraphicsEnvironment", emptyClassArr);
            Method getDefaultScreenDeviceMethod = graphicsEnvironmentClass.getMethod("getDefaultScreenDevice",
                    emptyClassArr);
            Method getDefaultConfigurationMethod = graphicsDeviceClass.getMethod("getDefaultConfiguration",
                    emptyClassArr);
            Method getBoundsMethod = graphicsConfigurationClass.getMethod("getBounds", emptyClassArr);
            Method getScreenInsetsMethod = Toolkit.class.getMethod("getScreenInsets",
                    new Class[] { graphicsConfigurationClass });

            Object[] emptyObjArr = new Object[0];
            Object graphicsEnvironment = getLocalGraphicsEnvironmentMethod.invoke(null, emptyObjArr);
            Object defaultScreenDevice = getDefaultScreenDeviceMethod.invoke(graphicsEnvironment, emptyObjArr);
            Object defaultConfiguration = getDefaultConfigurationMethod.invoke(defaultScreenDevice,
                    emptyObjArr);
            Rectangle bounds = (Rectangle) getBoundsMethod.invoke(defaultConfiguration, emptyObjArr);
            Insets insets = (Insets) getScreenInsetsMethod.invoke(Toolkit.getDefaultToolkit(),
                    new Object[] { defaultConfiguration });

            bounds.x += insets.left;
            bounds.y += insets.top;
            bounds.width -= insets.left + insets.right;
            bounds.height -= insets.top + insets.bottom;

            return bounds;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    return new Rectangle(new Point(0, 0), Toolkit.getDefaultToolkit().getScreenSize());
}

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.//from w w  w.  ja  v a 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 boolean hasDependentData(Class[] peerClasses, String[] fields, List<Integer> oldOIDs) {
    // Do this using reflection.
    if (oldOIDs == null || oldOIDs.isEmpty()) {
        return false;
    }
    Criteria selectCriteria;
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        List<int[]> chunkList = GeneralUtils.getListOfChunks(oldOIDs);
        Iterator<int[]> iterator = chunkList.iterator();
        while (iterator.hasNext()) {
            int[] oIDsChunk = iterator.next();
            selectCriteria = new Criteria();
            selectCriteria.addIn(field, oIDsChunk);
            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 " + "oldOIDs " + oldOIDs.size()
                        + " for class " + peerClass.toString() + " and field " + field + ": " + e.getMessage());
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
    return false;
}

From source file:com.softmotions.commons.bean.BeanUtils.java

/**
 * Gets a property from the given bean.// w ww .j  a  va  2  s .c o m
 *
 * @param clazz        The class to determine the property type for.
 * @param propertyName The name of the property to read.
 * @param lenient      If true is passed for this attribute, null will returned for
 *                     in case no matching getter method is defined, else an Exception will be throw
 *                     in this case.
 * @return The determined value.
 * @throws BeanException In case the bean access failed.
 */
public static Class getPropertyType(Class clazz, String propertyName, boolean lenient) throws BeanException {

    try {
        // getting property object from bean using "getNnnn", where nnnn is parameter name
        Method getterMethod = null;
        try {
            // first trying form getPropertyNaae for regular value
            String getterName = "get" + Character.toUpperCase(propertyName.charAt(0))
                    + propertyName.substring(1);
            getterMethod = clazz.getMethod(getterName, GETTER_ARG_TYPES);
        } catch (NoSuchMethodException ex) {
            // next trying isPropertyNaae for possible boolean
            String getterName = "is" + Character.toUpperCase(propertyName.charAt(0))
                    + propertyName.substring(1);
            getterMethod = clazz.getMethod(getterName, GETTER_ARG_TYPES);
        }
        return getterMethod.getReturnType();
    } catch (NoSuchMethodError | NoSuchMethodException ex) {
        if (!lenient) {
            throw new BeanException("Property '" + propertyName + "' is undefined for given bean from class "
                    + clazz.getName() + ".");
        }
    }
    return null;
}

From source file:cc.pp.analyzer.paoding.knife.PaodingMaker.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Paoding createPaodingWithKnives(Properties p) throws Exception {
    // PaodingHolderPaoding
    // ?Paoding?paodingHolder
    Paoding paoding = new Paoding();

    // Knife//from   w  w w .  j ava2  s .  com
    final Map /* <String, Knife> */ knifeMap = new HashMap /*
                                                           * <String,
                                                           * Knife>
                                                           */();
    final List /* <Knife> */ knifeList = new LinkedList/* <Knife> */();
    final List /* <Function> */<Function> functions = new LinkedList/* <Function> */();
    Iterator iter = p.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry e = (Map.Entry) iter.next();
        final String key = (String) e.getKey();
        final String value = (String) e.getValue();
        int index = key.indexOf(Constants.KNIFE_CLASS);
        if (index == 0 && key.length() > Constants.KNIFE_CLASS.length()) {
            final int end = key.indexOf('.', Constants.KNIFE_CLASS.length());
            if (end == -1) {
                Class clazz = Class.forName(value);
                Knife knife = (Knife) clazz.newInstance();
                knifeList.add(knife);
                knifeMap.put(key, knife);
                log.info("add knike: " + value);
            } else {
                // hashkey???????knife?
                // ?functionsknife??
                functions.add(new Function() {
                    @Override
                    public void run() throws Exception {
                        String knifeName = key.substring(0, end);
                        Object obj = knifeMap.get(knifeName);
                        if (!obj.getClass().getName().equals("org.springframework.beans.BeanWrapperImpl")) {
                            Class beanWrapperImplClass = Class
                                    .forName("org.springframework.beans.BeanWrapperImpl");
                            Method setWrappedInstance = beanWrapperImplClass.getMethod("setWrappedInstance",
                                    new Class[] { Object.class });
                            Object beanWrapperImpl = beanWrapperImplClass.newInstance();
                            setWrappedInstance.invoke(beanWrapperImpl, new Object[] { obj });
                            knifeMap.put(knifeName, beanWrapperImpl);
                            obj = beanWrapperImpl;
                        }
                        String propertyName = key.substring(end + 1);
                        Method setPropertyValue = obj.getClass().getMethod("setPropertyValue",
                                new Class[] { String.class, Object.class });
                        setPropertyValue.invoke(obj, new Object[] { propertyName, value });
                    }
                });
            }
        }
    }
    // ???
    for (Iterator iterator = functions.iterator(); iterator.hasNext();) {
        Function function = (Function) iterator.next();
        function.run();
    }
    // ?
    paoding.setKnives(knifeList);
    return paoding;
}