Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.github.gekoh.yagen.util.FieldInfo.java

public static AccessibleObject getIdFieldOrMethod(Class entityClass) {
    for (Field field : entityClass.getDeclaredFields()) {
        if (field.isAnnotationPresent(Id.class)) {
            return field;
        }/*ww w .  j av a2  s.  c  o  m*/
    }
    for (Method method : entityClass.getDeclaredMethods()) {
        if (method.isAnnotationPresent(Id.class)) {
            return method;
        }
    }
    return entityClass.getSuperclass() != null ? getIdFieldOrMethod(entityClass.getSuperclass()) : null;
}

From source file:org.apache.olingo.ext.proxy.utils.CoreUtils.java

private static String firstValidEntityKey(final Class<?> entityTypeRef) {
    for (Method method : entityTypeRef.getDeclaredMethods()) {
        if (method.getAnnotation(Key.class) != null) {
            final Annotation ann = method.getAnnotation(Property.class);
            if (ann != null) {
                return ((Property) ann).name();
            }/*from  w w  w  .  jav a 2s. c  o  m*/
        }
    }
    return null;
}

From source file:com.zhangwx.dynamicpermissionsrequest.permission.EasyPermissions.java

private static void runAnnotatedMethods(@NonNull Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();//from  w ww .  ja v a2s  .c om
    }

    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
                // Check for annotated methods with matching request code.
                AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
                if (ann.value() == requestCode) {
                    // Method must be void so that we can invoke it
                    if (method.getParameterTypes().length > 0) {
                        throw new RuntimeException("Cannot execute method " + method.getName()
                                + " because it is non-void method and/or has input parameters.");
                    }

                    try {
                        // Make method accessible if private
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(object);
                    } catch (IllegalAccessException e) {
                        Log.e(TAG, "runDefaultMethod:IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        Log.e(TAG, "runDefaultMethod:InvocationTargetException", e);
                    }
                }
            }
        }

        clazz = clazz.getSuperclass();
    }
}

From source file:Mopex.java

/**
 * Returns the method object for the unique method named mName. If no such
 * method exists, a null is returned. If there is more than one such method,
 * a runtime exception is thrown./* w w w  .  j  a va2s. c  o  m*/
 * 
 * @return Method
 * @param cls
 *            java.lang.Class
 * @param mName
 *            String
 */
public static Method getUniquelyNamedMethod(Class cls, String mName) {
    Method result = null;
    Method[] mArray = cls.getDeclaredMethods();
    for (int i = 0; i < mArray.length; i++)
        if (mName.equals(mArray[i].getName())) {
            if (result == null)
                result = mArray[i];
            else
                throw new RuntimeException("name is not unique");
        }
    return result;
}

From source file:cz.cuni.mff.d3s.spl.example.newton.app.Main.java

private static void inspectClass(Object obj) {
    if (!INSPECT) {
        return;//www . j a  va 2  s.c om
    }

    System.out.printf("Inspecting %s:\n", obj);
    Class<?> klass = obj.getClass();
    System.out.printf("  Class: %s\n", klass.getName());
    for (Field f : klass.getDeclaredFields()) {
        Object value;
        boolean accessible = f.isAccessible();
        try {
            f.setAccessible(true);
            value = f.get(obj);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            value = String.format("<failed to read: %s>", e.getMessage());
        }
        f.setAccessible(accessible);
        System.out.printf("  Field %s: %s\n", f.getName(), value);
    }
    for (Method m : klass.getDeclaredMethods()) {
        System.out.printf("  Method %s\n", m.getName());
    }
    System.out.printf("-------\n");
    System.out.flush();
}

From source file:com.aftabsikander.permissionassist.PermissionAssistant.java

private static void runAnnotatedMethods(@NonNull Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();/*from ww  w. j  a va 2 s. c  o  m*/
    }

    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
                // Check for annotated methods with matching request code.
                AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
                if (ann.value() == requestCode) {
                    // Method must be void so that we can invoke it
                    if (method.getParameterTypes().length > 0) {
                        throw new RuntimeException("Cannot execute method " + method.getName()
                                + " because it is non-void method and/or has input parameters.");
                    }
                    try {
                        // Make method accessible if private
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(object);
                    } catch (IllegalAccessException e) {
                        Log.e(TAG, "runDefaultMethod:IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        Log.e(TAG, "runDefaultMethod:InvocationTargetException", e);
                    }
                }
            }
        }

        clazz = clazz.getSuperclass();
    }
}

From source file:com.medallia.spider.api.StRenderer.java

/** @return the action method of the given class; throws AssertionError if no such method exists */
private static Method findActionMethod(Class<?> clazz) {
    Method am = ACTION_METHOD_MAP.get(clazz);
    if (am != null)
        return am;

    for (Method m : CollUtils.concat(Arrays.asList(clazz.getMethods()),
            Arrays.asList(clazz.getDeclaredMethods()))) {
        if (m.getName().equals("action")) {
            int modifiers = m.getModifiers();
            if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers))
                continue;
            m.setAccessible(true);/*from  ww  w .  j a  v a2s  . c o  m*/
            ACTION_METHOD_MAP.put(clazz, m);
            return m;
        }
    }
    throw new AssertionError("No action method found in " + clazz);
}

From source file:Main.java

/**
 * Force the given class to be loaded fully.
 * /*from  w  w  w.  j  ava  2 s . c o m*/
 * <p>
 * This method attempts to locate a static method on the given class the
 * attempts to invoke it with dummy arguments in the hope that the virtual
 * machine will prepare the class for the method call and call all of the
 * static class initializers.
 * 
 * @param type
 *          Class to force load.
 * 
 * @throws NullArgumentException
 *           Type is <i>null</i>.
 */
public static void forceLoad(final Class type) {
    if (type == null)
        System.out.println("Null Argument Exception");

    // don't attempt to force primitives to load
    if (type.isPrimitive())
        return;

    // don't attempt to force java.* classes to load
    String packageName = Classes.getPackageName(type);
    // System.out.println("package name: " + packageName);

    if (packageName.startsWith("java.") || packageName.startsWith("javax.")) {
        return;
    }

    // System.out.println("forcing class to load: " + type);

    try {
        Method methods[] = type.getDeclaredMethods();
        Method method = null;
        for (int i = 0; i < methods.length; i++) {
            int modifiers = methods[i].getModifiers();
            if (Modifier.isStatic(modifiers)) {
                method = methods[i];
                break;
            }
        }

        if (method != null) {
            method.invoke(null, (Object[]) null);
        } else {
            type.newInstance();
        }
    } catch (Exception ignore) {
        ignore.printStackTrace();
    }
}

From source file:org.alfresco.traitextender.AJExtender.java

/**
 * @param extensible/*from   w  w w  .  j  a va2  s .c  om*/
 * @return a compilation result containing all {@link Extend} mapped routes,
 *         not routed or dangling methods within the give extensible class.
 * @throws AJExtensibleCompilingException
 */
static CompiledExtensible compile(Class<? extends Extensible> extensible)
        throws AJExtensibleCompilingException {
    logger.info("Compiling extensible " + extensible);

    CompiledExtensible compiledExtensible = new CompiledExtensible(extensible);

    List<Method> methods = new ArrayList<>();
    Class<?> extendDeclaring = extensible;
    while (extendDeclaring != null) {
        Method[] declaredMethods = extendDeclaring.getDeclaredMethods();
        methods.addAll(Arrays.asList(declaredMethods));
        extendDeclaring = extendDeclaring.getSuperclass();
    }
    Set<Extend> extendDeclarations = new HashSet<>();
    Set<Method> routedExtensionMethods = new HashSet<>();
    for (Method method : methods) {

        Extend extend = method.getAnnotation(Extend.class);
        if (extend != null) {
            try {
                extendDeclarations.add(extend);
                Class<?> extensionAPI = extend.extensionAPI();
                Method extensionMethod = extensionAPI.getMethod(method.getName(), method.getParameterTypes());
                compiledExtensible.add(new ExtensionRoute(extend, method, extensionMethod));
                routedExtensionMethods.add(extensionMethod);
            } catch (NoSuchMethodException error) {
                AJExtensibleCompilingException ajCompilingError = new AJExtensibleCompilingException(
                        "No route for " + method.toGenericString() + " @" + extend, error);
                compiledExtensible.add(ajCompilingError);
            } catch (SecurityException error) {
                AJExtensibleCompilingException ajCompilingError = new AJExtensibleCompilingException(
                        "Access denined to route for " + method.toGenericString() + " @" + extend, error);
                compiledExtensible.add(ajCompilingError);
            }
        }

    }

    final Set<Method> allObjectMethods = new HashSet<>(Arrays.asList(Object.class.getMethods()));

    for (Extend extend : extendDeclarations) {
        Class<?> extension = extend.extensionAPI();

        Set<Method> allExtensionMethods = new HashSet<>(Arrays.asList(extension.getMethods()));
        allExtensionMethods.removeAll(allObjectMethods);
        allExtensionMethods.removeAll(routedExtensionMethods);
        if (!allExtensionMethods.isEmpty()) {
            for (Method method : allExtensionMethods) {
                compiledExtensible.add(new AJDanglingExtensionError(method, extend));
            }
        }
    }

    logger.info(compiledExtensible.getInfo());

    return compiledExtensible;
}

From source file:com.startechup.tools.ModelParser.java

/**
 * Gets the values from the {@link JSONObject JSONObjects}/response returned from an api call
 * request and assign it to the field inside the class that will contain the parsed values.
 *
 * @param classModel The class type that will contain the parse value.
 * @param jsonObject The API response object.
 * @return Returns a generic class containing the values from the json, null if exception occurs.
 *//*w  ww.j a  v a  2s.  c  om*/
public static <T> T parse(Class<T> classModel, JSONObject jsonObject) {
    Object object = getNewInstance(classModel);

    if (object != null) {
        // TODO this solution is much accurate but not flexible when using a 3rd party library
        // for object model creation like squidb from yahoo, annotation should be added to the class method
        // and we cannot do that on squidb generated Class model.
        for (Method method : classModel.getDeclaredMethods()) {
            if (method.isAnnotationPresent(SetterSpec.class)) {
                SetterSpec methodLinker = method.getAnnotation(SetterSpec.class);
                String jsonKey = methodLinker.jsonKey();

                initMethodInvocation(method, object, jsonKey, jsonObject);
            }
        }
        return classModel.cast(object);
    } else {
        return null;
    }
}