Example usage for java.lang.reflect Method getModifiers

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

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:edu.ku.brc.af.ui.forms.FormHelper.java

public static void dumpDataObj(final DataProviderSessionIFace session, final Object dataObj,
        final Hashtable<Class<?>, Boolean> clsHash, final int level) {
    if (dataObj == null || clsHash.get(dataObj.getClass()) != null)
        return;// w ww  .  java2s.  co  m

    String clsName = dataObj.getClass().toString();
    if (clsName.indexOf("CGLIB") > -1)
        return;

    StringBuilder indent = new StringBuilder();
    for (int i = 0; i < level; i++)
        indent.append("  ");

    for (Method method : dataObj.getClass().getMethods()) {
        String methodName = method.getName();
        if (!methodName.startsWith("get") || method.getModifiers() == 9) {
            continue;
        }

        String fieldName = methodName.substring(3, 4).toLowerCase()
                + methodName.substring(4, methodName.length());
        Object kidData = null;
        try {
            kidData = getValue((FormDataObjIFace) dataObj, fieldName);

        } catch (Exception ex) {
            System.out.println(indent + fieldName + " = <no data>");
        }
        if (kidData != null) {
            if (kidData instanceof Set<?>) {
                for (Object obj : ((Set<?>) kidData)) {
                    System.out.println(indent + fieldName + " = " + obj);
                    if (obj instanceof FormDataObjIFace) {
                        dumpDataObj(session, obj, clsHash, level + 1);
                    }
                }
            } else {
                System.out.println(indent + fieldName + " = " + kidData);
                if (kidData instanceof FormDataObjIFace) {
                    session.attach(kidData);
                    dumpDataObj(session, kidData, clsHash, level + 1);
                }
            }

        }

    }
}

From source file:dk.netarkivet.common.utils.ApplicationUtils.java

/**
 * Starts up an application. The applications class must:
 * (i) Have a static getInstance() method which returns a
 *     an instance of itself.//www  .j a va 2 s .  c  o  m
 * (ii) Implement CleanupIF.
 * If the class cannot be started and a shutdown hook added, the JVM
 * exits with a return code depending on the problem:
 * 1 means wrong arguments
 * 2 means no factory method exists for class
 * 3 means couldn't instantiate class
 * 4 means couldn't add shutdown hook
 * 5 means couldn't add liveness logger
 * 6 means couldn't add remote management
 * @param c The class to be started.
 * @param args The arguments to the application (should be empty).
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void startApp(Class c, String[] args) {
    String appName = c.getName();
    Settings.set(CommonSettings.APPLICATION_NAME, appName);
    logAndPrint("Starting " + appName + "\n" + Constants.getVersionString());
    log.info("Using settings files '" + StringUtils.conjoin(File.pathSeparator, Settings.getSettingsFiles())
            + "'");
    checkArgs(args);
    dirMustExist(FileUtils.getTempDir());
    Method factoryMethod = null;
    CleanupIF instance = null;
    // Start the remote management connector
    try {
        MBeanConnectorCreator.exposeJMXMBeanServer();
        log.trace("Added remote management for " + appName);
    } catch (Throwable e) {
        logExceptionAndPrint("Could not add remote management for class " + appName, e);
        System.exit(EXCEPTION_WHEN_ADDING_MANAGEMENT);
    }
    // Get the factory method
    try {
        factoryMethod = c.getMethod("getInstance", (Class[]) null);
        int modifier = factoryMethod.getModifiers();
        if (!Modifier.isStatic(modifier)) {
            throw new Exception("getInstance is not static");
        }
        logAndPrint(appName + " Running");
    } catch (Throwable e) {
        logExceptionAndPrint("Class " + appName + " does not have required" + "factory method", e);
        System.exit(NO_FACTORY_METHOD);
    }
    // Invoke the factory method
    try {
        log.trace("Invoking factory method.");
        instance = (CleanupIF) factoryMethod.invoke(null, (Object[]) null);
        log.trace("Factory method invoked.");
    } catch (Throwable e) {
        logExceptionAndPrint("Could not start class " + appName, e);
        System.exit(EXCEPTION_WHILE_INSTANTIATING);
    }
    // Add the shutdown hook
    try {
        log.trace("Adding shutdown hook for " + appName);
        Runtime.getRuntime().addShutdownHook((new CleanupHook(instance)));
        log.trace("Added shutdown hook for " + appName);
    } catch (Throwable e) {
        logExceptionAndPrint("Could not add shutdown hook for class " + appName, e);
        System.exit(EXCEPTION_WHEN_ADDING_SHUTDOWN_HOOK);
    }
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

/**
 * Between two getter methods defined for a given property, both declared in the same class, picks one
 *
 * @param first  the first getter// w  ww. j a v a 2 s . com
 * @param second the second getter
 * @return the winning getter
 */
private static Method pickGetter(Method first, Method second) {
    //if one is an interface, and one is not, the concrete implementation wins
    if (Modifier.isInterface(first.getModifiers()) && !Modifier.isInterface(second.getModifiers())) {
        return second;
    }
    if (!Modifier.isInterface(first.getModifiers()) && Modifier.isInterface(second.getModifiers())) {
        return first;
    }
    //if one is abstract and the other is not, the non-abstract one wins
    if (Modifier.isAbstract(first.getModifiers()) && !Modifier.isAbstract(second.getModifiers())) {
        return second;
    }
    if (!Modifier.isAbstract(first.getModifiers()) && Modifier.isAbstract(second.getModifiers())) {
        return first;
    }
    //given a hierarchy, the child wins
    if (first.getReturnType().isAssignableFrom(second.getReturnType())) {
        return second;
    }
    if (second.getReturnType().isAssignableFrom(first.getReturnType())) {
        return first;
    }
    if (!hasAnnotations(first) && hasAnnotations(second)) {
        return second;
    }
    if (hasAnnotations(first) && !hasAnnotations(second)) {
        return first;
    }
    return first;
}

From source file:com.taobao.weex.wson.Wson.java

private static final List<Method> getBeanMethod(String key, Class targetClass) {
    List<Method> methods = methodsCache.get(key);
    if (methods == null) {
        methods = new ArrayList<>();
        Method[] allMethods = targetClass.getMethods();
        for (Method method : allMethods) {
            if (method.getDeclaringClass() == Object.class) {
                continue;
            }//from   ww w .  j ava  2  s . co  m
            if ((method.getModifiers() & Modifier.STATIC) != 0) {
                continue;
            }
            String methodName = method.getName();
            if (methodName.startsWith(METHOD_PREFIX_GET) || methodName.startsWith(METHOD_PREFIX_IS)) {
                if (method.getAnnotation(JSONField.class) != null) {
                    throw new UnsupportedOperationException(
                            "getBeanMethod JSONField Annotation Not Handled, Use toJSON");
                }
                methods.add(method);
            }
        }
        methodsCache.put(key, methods);
    }
    return methods;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Determine whether the method is declared public static
 * @param m//from   ww w .ja v  a2  s .c o  m
 * @return True if the method is declared public static
 */
public static boolean isPublicStatic(Method m) {
    final int modifiers = m.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
}

From source file:com.sun.faces.el.impl.BeanInfoManager.java

/**
 * If the given class is public and has a Method that declares the
 * same name and arguments as the given method, then that method is
 * returned.  Otherwise the superclass and interfaces are searched
 * recursively./*from   w  w  w.  j a va2  s  .  c  om*/
 */
static Method getPublicMethod(Class pClass, Method pMethod) {
    // See if this is a public class declaring the method
    if (Modifier.isPublic(pClass.getModifiers())) {
        try {
            Method m;
            try {
                m = pClass.getDeclaredMethod(pMethod.getName(), pMethod.getParameterTypes());
            } catch (java.security.AccessControlException ex) {
                // kludge to accommodate J2EE RI's default settings
                // TODO: see if we can simply replace
                //       getDeclaredMethod() with getMethod() ...?
                m = pClass.getMethod(pMethod.getName(), pMethod.getParameterTypes());
            }
            if (Modifier.isPublic(m.getModifiers())) {
                return m;
            }
        } catch (NoSuchMethodException exc) {
        }
    }

    // Search the interfaces
    {
        Class[] interfaces = pClass.getInterfaces();
        if (interfaces != null) {
            for (int i = 0; i < interfaces.length; i++) {
                Method m = getPublicMethod(interfaces[i], pMethod);
                if (m != null) {
                    return m;
                }
            }
        }
    }

    // Search the superclass
    {
        Class superclass = pClass.getSuperclass();
        if (superclass != null) {
            Method m = getPublicMethod(superclass, pMethod);
            if (m != null) {
                return m;
            }
        }
    }

    return null;
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static List findMutatorMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne && isPublic;
        }//from w  ww. ja  va  2s .com
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static List findOtherPublicMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return ((startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne) == false) && isPublic;
        }/*w ww.  j a v a  2 s . c  om*/
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:org.apache.brooklyn.util.javalang.MethodAccessibleReflections.java

/**
 * @see {@link Reflections#findAccessibleMethod(Method)}
 *//* ww  w  . j a  va 2 s  . co  m*/
// Similar to org.apache.commons.lang3.reflect.MethodUtils.getAccessibleMethod
// We could delegate to that, but currently brooklyn-utils-common doesn't depend on commons-lang3; maybe it should?
static Maybe<Method> findAccessibleMethod(Method method) {
    if (!isAccessible(method)) {
        String err = "Method is not public, so not normally accessible for " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err + "; usage may subsequently fail");
        }
        return Maybe.absent(err);
    }

    boolean declaringClassAccessible = isAccessible(method.getDeclaringClass());
    if (declaringClassAccessible) {
        return Maybe.of(method);
    }

    // reflectively calling a public method on a private class can fail (unless one first 
    // calls setAccessible). Check if this overrides a public method on a public super-type
    // that we can call instead!

    if (Modifier.isStatic(method.getModifiers())) {
        String err = "Static method not declared on a public class, so not normally accessible for " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err + "; usage may subsequently fail");
        }
        return Maybe.absent(err);
    }

    Maybe<Method> altMethod = tryFindAccessibleEquivalent(method);

    if (altMethod.isPresent()) {
        LOG.debug("Switched method for publicly accessible equivalent: method={}; origMethod={}",
                altMethod.get(), method);
        return altMethod;
    } else {
        String err = "No accessible (overridden) method found in public super-types for method " + method;
        if (FIND_ACCESSIBLE_FAILED_LOGGED_METHODS.add(method.toString())) {
            LOG.warn(err);
        }
        return Maybe.absent(err);
    }
}

From source file:com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils.java

/**
 * Not really a generic method for printing random object graphs. But it
 * works for events and decisions.//from  w w  w.  j a va2 s. c o  m
 */
private static String prettyPrintObject(Object object, String methodToSkip,
        boolean skipNullsAndEmptyCollections, String indentation, boolean skipLevel) {
    StringBuffer result = new StringBuffer();
    if (object == null) {
        return "null";
    }
    Class<? extends Object> clz = object.getClass();
    if (Number.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Boolean.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (clz.equals(String.class)) {
        return (String) object;
    }
    if (clz.equals(Date.class)) {
        return String.valueOf(object);
    }
    if (Map.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (Collection.class.isAssignableFrom(clz)) {
        return String.valueOf(object);
    }
    if (!skipLevel) {
        result.append(" {");
    }
    Method[] eventMethods = object.getClass().getMethods();
    boolean first = true;
    for (Method method : eventMethods) {
        String name = method.getName();
        if (!name.startsWith("get")) {
            continue;
        }
        if (name.equals(methodToSkip) || name.equals("getClass")) {
            continue;
        }
        if (Modifier.isStatic(method.getModifiers())) {
            continue;
        }
        Object value;
        try {
            value = method.invoke(object, (Object[]) null);
            if (value != null && value.getClass().equals(String.class) && name.equals("getDetails")) {
                value = printDetails((String) value);
            }
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e.getTargetException());
        } catch (RuntimeException e) {
            throw (RuntimeException) e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (skipNullsAndEmptyCollections) {
            if (value == null) {
                continue;
            }
            if (value instanceof Map && ((Map<?, ?>) value).isEmpty()) {
                continue;
            }
            if (value instanceof Collection && ((Collection<?>) value).isEmpty()) {
                continue;
            }
        }
        if (!skipLevel) {
            if (first) {
                first = false;
            } else {
                result.append(";");
            }
            result.append("\n");
            result.append(indentation);
            result.append("    ");
            result.append(name.substring(3));
            result.append(" = ");
            result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections,
                    indentation + "    ", false));
        } else {
            result.append(
                    prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation, false));
        }
    }
    if (!skipLevel) {
        result.append("\n");
        result.append(indentation);
        result.append("}");
    }
    return result.toString();
}