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:nz.co.senanque.validationengine.ValidationUtils.java

public static Method figureValueOf(final Class<?> clazz) {
    Method method = null;//from   w w  w  . jav a  2 s.  c o m
    try {
        method = clazz.getMethod("valueOf", java.lang.String.class);
    } catch (Exception e) {
    }
    return method;
}

From source file:com.dicksoft.ocr.xml.Parser.java

/**
 * Download and parse the specified data set.
 * /* w  ww.  ja  v a  2 s  .c o  m*/
 * @param <T>
 * @param clazz
 *            the Class of the type to be parsed
 * @param elements
 *            the set of elements to add parsed data to
 * @throws NotParseableException
 *             if the contract of Parseable is breached
 */
public static <T extends Parseable> void parse(Class<T> clazz, Set<T> elements) throws NotParseableException {
    int numElements = 0;
    try {
        numElements = parseSize(
                (String) clazz.getMethod(Parseable.LIST_URL_METHOD, new Class[0]).invoke(null, new Object[0]));
        for (int i = 0; i < numElements; i++) {
            String xml = null;
            try {
                xml = HttpUtil.fetchText(
                        (String) clazz.getMethod(Parseable.ELEMENT_URL_METHOD, new Class[] { Integer.TYPE })
                                .invoke(null, new Object[] { i }));
            } catch (IOException e) {
                LOG.debug("Composer with ID " + i + "was not found.");
                continue;
            }
            elements.add(clazz.cast(
                    clazz.getMethod("parse", new Class[] { String.class }).invoke(null, new Object[] { xml })));
        }
    } catch (IllegalArgumentException e) {
        throw new NotParseableException(e);
    } catch (SecurityException e) {
        throw new NotParseableException(e);
    } catch (IllegalAccessException e) {
        throw new NotParseableException(e);
    } catch (InvocationTargetException e) {
        throw new NotParseableException(e);
    } catch (NoSuchMethodException e) {
        throw new NotParseableException(e);
    }
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

public static File dex(List<File> files, File distFile) throws Exception {
    String dxJar = "src/test/resources/dx.jar";
    File dxFile = new File(dxJar);
    if (!dxFile.exists()) {
        throw new RuntimeException("dx.jar?");
    }//from  w  w w.ja  v a 2 s . c om
    URLClassLoader cl = new URLClassLoader(new URL[] { dxFile.toURI().toURL() });
    Class<?> c = cl.loadClass("com.android.dx.command.Main");
    Method m = c.getMethod("main", String[].class);

    if (distFile == null) {
        distFile = File.createTempFile("dex", ".dex");
    }
    List<String> args = new ArrayList<String>();
    args.addAll(Arrays.asList("--dex", "--no-strict", "--output=" + distFile.getCanonicalPath()));
    for (File f : files) {
        args.add(f.getCanonicalPath());
    }
    m.invoke(null, new Object[] { args.toArray(new String[0]) });
    return distFile;
}

From source file:com.haulmont.bali.util.ReflectionHelper.java

/**
 * Invokes a method by reflection.// w w  w  .jav  a  2 s  .  com
 * @param obj       object instance
 * @param name      method name
 * @param params    method arguments
 * @return          method result
 * @throws NoSuchMethodException if a suitable method not found
 */
public static <T> T invokeMethod(Object obj, String name, Object... params) throws NoSuchMethodException {
    Class[] paramTypes = getParamTypes(params);

    final Class<?> aClass = obj.getClass();
    Method method;
    try {
        method = aClass.getDeclaredMethod(name, paramTypes);
    } catch (NoSuchMethodException e) {
        method = aClass.getMethod(name, paramTypes);
    }
    method.setAccessible(true);
    try {
        //noinspection unchecked
        return (T) method.invoke(obj, params);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

/**
 * search the method and return the defined method.
 * it will {@link Class#getMethod(String, Class[])}, if exception occurs,
 * it will search for all methods, and find the most fit method.
 *///from  w w w  . j  a v a  2s  .  c  o  m
public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes, boolean boxed)
        throws NoSuchMethodException {
    if (currentClass == null) {
        throw new NoSuchMethodException("class == null");
    }
    try {
        return currentClass.getMethod(name, parameterTypes);
    } catch (NoSuchMethodException e) {
        Method likeMethod = null;
        for (Method method : currentClass.getMethods()) {
            if (method.getName().equals(name) && parameterTypes.length == method.getParameterTypes().length
                    && Modifier.isPublic(method.getModifiers())) {
                if (parameterTypes.length > 0) {
                    Class<?>[] types = method.getParameterTypes();
                    boolean eq = true;
                    boolean like = true;
                    for (int i = 0; i < parameterTypes.length; i++) {
                        Class<?> type = types[i];
                        Class<?> parameterType = parameterTypes[i];
                        if (type != null && parameterType != null && !type.equals(parameterType)) {
                            eq = false;
                            if (boxed) {
                                type = getBoxedClass(type);
                                parameterType = getBoxedClass(parameterType);
                            }
                            if (!type.isAssignableFrom(parameterType)) {
                                eq = false;
                                like = false;
                                break;
                            }
                        }
                    }
                    if (!eq) {
                        if (like && (likeMethod == null || likeMethod.getParameterTypes()[0]
                                .isAssignableFrom(method.getParameterTypes()[0]))) {
                            likeMethod = method;
                        }
                        continue;
                    }
                }
                return method;
            }
        }
        if (likeMethod != null) {
            return likeMethod;
        }
        throw e;
    }
}

From source file:net.menthor.editor.v2.util.Util.java

public static void enableFullScreenMode(Window window) {
    String className = "com.apple.eawt.FullScreenUtilities";
    String methodName = "setWindowCanFullScreen";
    try {/*from  ww  w.ja va 2  s.  c o m*/
        Class<?> clazz = Class.forName(className);
        Method method = clazz.getMethod(methodName, new Class<?>[] { Window.class, boolean.class });
        method.invoke(null, window, true);
    } catch (Throwable t) {
        System.err.println("Full screen mode is not supported");
        t.printStackTrace();
    }
}

From source file:Main.java

public static String getDefaultRealm() throws ClassNotFoundException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    Object kerbConf;/*from ww w . j ava 2s. co m*/
    Class<?> classRef;
    Method getInstanceMethod;
    Method getDefaultRealmMethod;
    if (System.getProperty("java.vendor").contains("IBM")) {
        classRef = Class.forName("com.ibm.security.krb5.internal.Config");
    } else {
        classRef = Class.forName("sun.security.krb5.Config");
    }
    getInstanceMethod = classRef.getMethod("getInstance", new Class[0]);
    kerbConf = getInstanceMethod.invoke(classRef, new Object[0]);
    getDefaultRealmMethod = classRef.getDeclaredMethod("getDefaultRealm", new Class[0]);
    return (String) getDefaultRealmMethod.invoke(kerbConf, new Object[0]);
}

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

/**
 * Gets a property from the given bean./*w  w w .j av  a 2 s.  c o m*/
 *
 * @param bean         The bean to read property from.
 * @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 Object getProperty(Object bean, 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);
            Class paramClass = bean.getClass();
            getterMethod = paramClass.getMethod(getterName, GETTER_ARG_TYPES);
        } catch (NoSuchMethodException ignored) {
            // next trying isPropertyNaae for possible boolean
            String getterName = "is" + Character.toUpperCase(propertyName.charAt(0))
                    + propertyName.substring(1);
            Class paramClass = bean.getClass();
            getterMethod = paramClass.getMethod(getterName, GETTER_ARG_TYPES);
        }
        return getterMethod.invoke(bean, GETTER_ARGS);
    } catch (NoSuchMethodError ex) {
        if (!lenient) {
            throw new BeanException("Property '" + propertyName + "' is undefined for given bean from class "
                    + bean.getClass().getName() + ".", ex);
        }
    } catch (NoSuchMethodException ignored) {
        if (!lenient) {
            throw new BeanException("Property '" + propertyName + "' is undefined for given bean from class "
                    + bean.getClass().getName() + ".");
        }
    } catch (InvocationTargetException ex) {
        throw new BeanException("Property '" + propertyName
                + "' could not be evaluated for given bean from class " + bean.getClass().getName() + ".", ex);
    } catch (IllegalAccessException ex) {
        throw new BeanException("Property '" + propertyName
                + "' could not be accessed for given bean from class " + bean.getClass().getName() + ".", ex);
    }
    return null;
}

From source file:org.echocat.jemoni.jmx.support.SpringUtils.java

@Nullable
private static Method getMethod(@Nullable Class<?> fromType, boolean expectedStatic, Class<?> returnType,
        @Nonnull String name, @Nullable Class<?>... parameterTypes) {
    final Method method;
    if (fromType != null) {
        try {/*from   w  w w. j  a  v a  2s. c  om*/
            method = fromType.getMethod(name, parameterTypes);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(
                    buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes), e);
        }
        final int modifiers = method.getModifiers();
        if ((expectedStatic && !isStatic(modifiers)) || (!expectedStatic && isStatic(modifiers))
                || !returnType.isAssignableFrom(method.getReturnType())) {
            throw new RuntimeException(
                    buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes));
        }
    } else {
        method = null;
    }
    return method;
}

From source file:at.ait.dme.magicktiler.MagickTilerCLI.java

private static boolean showGui(String... args) {
    boolean displayGui = false;
    try {//from  w  ww.  j  a  v a 2 s. co m
        if (displayGui = Arrays.asList(args).contains("-g")) {
            // the gui can be removed from the build, which is why 
            // we try to load it dynamically here.
            Class<?> gui = Class.forName("at.ait.dme.magicktiler.gui.MagickTilerGUI");
            Method startup = gui.getMethod("startup", new Class[] { String[].class });
            startup.invoke(gui.newInstance(), new Object[] { args });
        }
    } catch (Exception e) {
        System.err.println("Failed to start GUI (did you exclude it from the build?): " + e);
    }
    return displayGui;
}