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:bammerbom.ultimatecore.bukkit.configuration.ConfigurationSerialization.java

protected Method getMethod(String name, boolean isStatic) {
    try {//from w ww. j  a v a 2  s .c  o  m
        Method method = clazz.getDeclaredMethod(name, Map.class);

        if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
            return null;
        }
        if (Modifier.isStatic(method.getModifiers()) != isStatic) {
            return null;
        }

        return method;
    } catch (NoSuchMethodException ex) {
        return null;
    } catch (SecurityException ex) {
        return null;
    }
}

From source file:cn.webwheel.DefaultMain.java

private Action getAction(Class cls, Method method) {
    if (Modifier.isStatic(method.getModifiers())) {
        return method.getAnnotation(Action.class);
    }// w w  w  .  ja v  a2 s .c  om
    ArrayList<Action> actions = new ArrayList<Action>();
    getActions(actions, new HashSet<Class>(), cls, method);
    if (actions.isEmpty())
        return null;
    if (actions.get(0).disabled())
        return null;
    if (actions.size() == 1)
        return actions.get(0);
    ActionImpl action = new ActionImpl();
    for (Action act : actions) {
        if (action.merge(act)) {
            return action;
        }
    }
    return action;
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

/**
 * @return true if m is not null and is abstract.
 *//*  ww  w .j ava2s .  c  o  m*/
public boolean isAbstract(Method m) {
    if (m == null)
        return false;

    return Modifier.isAbstract(m.getModifiers());
}

From source file:com.strandls.alchemy.rest.client.AlchemyRestClientFactoryTest.java

/**
 * Test method for/*  w w w.j  ava2  s. co  m*/
 * {@link com.strandls.alchemy.rest.client.AlchemyRestClientFactory#getInstance(java.lang.Class, java.lang.String, javax.ws.rs.client.Client)}
 * .
 *
 * Test get and post methods with a combination of parameter types (query,
 * path, header, cookie, matrix)
 *
 * @throws Exception
 */
@Test
public void testGetInstanceStub() throws Exception {
    final TestWebserviceWithPathStub service = clientFactory.getInstance(TestWebserviceWithPathStub.class);

    final Random r = new Random();

    final int[] args = new int[] { r.nextInt(), r.nextInt(), r.nextInt() };
    @SuppressWarnings("unchecked")
    final Set<Method> methods = ReflectionUtils.getAllMethods(TestWebserviceWithPathStub.class,
            new Predicate<Method>() {
                @Override
                public boolean apply(final Method input) {
                    return Modifier.isPublic(input.getModifiers());
                }
            });

    for (final Method method : methods) {
        System.out.println("Invoking : " + method);
        if (method.getParameterTypes().length == 3) {
            assertArrayEquals("Invocation failed on " + method, args,
                    (int[]) method.invoke(service, args[0], args[1], args[2]));
        } else {
            assertArrayEquals("Invocation failed on " + method, args, (int[]) method.invoke(service, args));
        }
        System.out.println("Done invoking : " + method);
    }
}

From source file:org.apache.tapestry.enhance.ComponentClassFactory.java

/**
 * @return true if m is not null and not abstract  
 *///from  w ww .  j  ava 2s . c  o  m
public boolean isImplemented(Method m) {
    if (m == null)
        return false;

    return !Modifier.isAbstract(m.getModifiers());
}

From source file:org.apache.hadoop.fs.TestFilterFileSystem.java

@Test
public void testFilterFileSystem() throws Exception {
    for (Method m : FileSystem.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()))
            continue;
        if (Modifier.isPrivate(m.getModifiers()))
            continue;
        if (Modifier.isFinal(m.getModifiers()))
            continue;

        try {//from  w ww  .j av a2s  .  c  o m
            DontCheck.class.getMethod(m.getName(), m.getParameterTypes());
            LOG.info("Skipping " + m);
        } catch (NoSuchMethodException exc) {
            LOG.info("Testing " + m);
            try {
                FilterFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
            } catch (NoSuchMethodException exc2) {
                LOG.error("FilterFileSystem doesn't implement " + m);
                throw exc2;
            }
        }
    }
}

From source file:com.strandls.alchemy.rest.client.AlchemyRestClientFactoryTest.java

/**
 * Test method for//from  w  w  w  . j a  v a 2s . c om
 * {@link com.strandls.alchemy.rest.client.AlchemyRestClientFactory#getInstance(java.lang.Class, java.lang.String, javax.ws.rs.client.Client)}
 * .
 *
 * Test get and post methods with a combination of parameter types (query,
 * path, header, cookie, matrix)
 *
 * @throws Exception
 */
@Test
public void testGetInstanceGetAndPost() throws Exception {
    final TestWebserviceWithPath service = clientFactory.getInstance(TestWebserviceWithPath.class);

    final Random r = new Random();

    final int[] args = new int[] { r.nextInt(), r.nextInt(), r.nextInt() };
    @SuppressWarnings("unchecked")
    final Set<Method> methods = ReflectionUtils.getAllMethods(TestWebserviceWithPath.class,
            new Predicate<Method>() {
                @Override
                public boolean apply(final Method input) {
                    return Modifier.isPublic(input.getModifiers());
                }
            });

    for (final Method method : methods) {
        System.out.println("Invoking : " + method);
        if (method.getParameterTypes().length == 3) {
            assertArrayEquals("Invocation failed on " + method, args,
                    (int[]) method.invoke(service, args[0], args[1], args[2]));
        } else if (method.getParameterTypes().length == 0) {
            method.invoke(service);
        } else {
            assertArrayEquals("Invocation failed on " + method, args, (int[]) method.invoke(service, args));
        }
        System.out.println("Done invoking : " + method);
    }
}

From source file:org.apache.syncope.core.logic.LoggerLogic.java

@PreAuthorize("hasRole('" + StandardEntitlement.AUDIT_LIST + "') or hasRole('"
        + StandardEntitlement.NOTIFICATION_LIST + "')")
public List<EventCategoryTO> listAuditEvents() {
    // use set to avoid duplications or null elements
    Set<EventCategoryTO> events = new HashSet<>();

    try {// w w w.j  a va 2s . c  o  m
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver);

        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(
                        SystemPropertyUtils.resolvePlaceholders(this.getClass().getPackage().getName()))
                + "/**/*.class";

        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                final Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());

                if (clazz.isAnnotationPresent(Component.class) && AbstractLogic.class.isAssignableFrom(clazz)) {
                    EventCategoryTO eventCategoryTO = new EventCategoryTO();
                    eventCategoryTO.setCategory(clazz.getSimpleName());
                    for (Method method : clazz.getDeclaredMethods()) {
                        if (Modifier.isPublic(method.getModifiers())) {
                            eventCategoryTO.getEvents().add(method.getName());
                        }
                    }
                    events.add(eventCategoryTO);
                }
            }
        }

        // SYNCOPE-608
        EventCategoryTO authenticationControllerEvents = new EventCategoryTO();
        authenticationControllerEvents.setCategory(AuditElements.AUTHENTICATION_CATEGORY);
        authenticationControllerEvents.getEvents().add(AuditElements.LOGIN_EVENT);
        events.add(authenticationControllerEvents);

        events.add(new EventCategoryTO(EventCategoryType.PROPAGATION));
        events.add(new EventCategoryTO(EventCategoryType.PULL));
        events.add(new EventCategoryTO(EventCategoryType.PUSH));

        for (AnyTypeKind anyTypeKind : AnyTypeKind.values()) {
            for (ExternalResource resource : resourceDAO.findAll()) {
                EventCategoryTO propEventCategoryTO = new EventCategoryTO(EventCategoryType.PROPAGATION);
                EventCategoryTO syncEventCategoryTO = new EventCategoryTO(EventCategoryType.PULL);
                EventCategoryTO pushEventCategoryTO = new EventCategoryTO(EventCategoryType.PUSH);

                propEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                propEventCategoryTO.setSubcategory(resource.getKey());

                syncEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                pushEventCategoryTO.setCategory(anyTypeKind.name().toLowerCase());
                syncEventCategoryTO.setSubcategory(resource.getKey());
                pushEventCategoryTO.setSubcategory(resource.getKey());

                for (ResourceOperation resourceOperation : ResourceOperation.values()) {
                    propEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    syncEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                    pushEventCategoryTO.getEvents().add(resourceOperation.name().toLowerCase());
                }

                for (UnmatchingRule unmatching : UnmatchingRule.values()) {
                    String event = UnmatchingRule.toEventName(unmatching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                for (MatchingRule matching : MatchingRule.values()) {
                    String event = MatchingRule.toEventName(matching);
                    syncEventCategoryTO.getEvents().add(event);
                    pushEventCategoryTO.getEvents().add(event);
                }

                events.add(propEventCategoryTO);
                events.add(syncEventCategoryTO);
                events.add(pushEventCategoryTO);
            }
        }

        for (SchedTask task : taskDAO.<SchedTask>findAll(TaskType.SCHEDULED)) {
            EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
            eventCategoryTO.setCategory(Class.forName(task.getJobDelegateClassName()).getSimpleName());
            events.add(eventCategoryTO);
        }

        EventCategoryTO eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PullJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);

        eventCategoryTO = new EventCategoryTO(EventCategoryType.TASK);
        eventCategoryTO.setCategory(PushJobDelegate.class.getSimpleName());
        events.add(eventCategoryTO);
    } catch (Exception e) {
        LOG.error("Failure retrieving audit/notification events", e);
    }

    return new ArrayList<>(events);
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();/*  www . j  av a  2 s.c om*/
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

From source file:org.carewebframework.cal.ui.reporting.drilldown.DrillDownDisplay.java

/**
 * When debug is true, dataObject is interrogated and the classes get/bean methods are invoked
 * and displayed on the display as well.
 *
 * @param dataObject Object to interrogate.
 * @param checkOnly If true, only checks to see if the object has additional debug info.
 * @return True if the object is a type for which additional debug info is available..
 *//* www .j a v a  2 s .co  m*/
private boolean debugObject(Object dataObject, boolean checkOnly) {
    if (dataObject != null) {
        Row row;
        Class<?> clazz = dataObject.getClass();

        if (!checkOnly) {
            log.debug("Adding Verbose DrillDown Object Debug Information");
            addRow("-------DEBUG--------", clazz.getName());
            row = getLastRow();
            row.appendChild(new Label());
            row.setSclass(Constants.SCLASS_DRILLDOWN_GRID);
        }

        try {
            Object[] params = null;
            //Method[] methods = clazz.getDeclaredMethods();
            Method[] methods = clazz.getMethods();

            if (!(dataObject instanceof String)) {
                for (Method method : methods) {
                    if (Modifier.PUBLIC == method.getModifiers()) {
                        // Assumes getter methods
                        if (method.getName().startsWith("get")
                                && method.getGenericParameterTypes().length == 0) {
                            if (checkOnly) {
                                return true;
                            }

                            Object invokedObject = method.invoke(getDataObject(), params);
                            String methodName = method.getName();
                            addRowViaObject(methodName, invokedObject);
                            addLink(invokedObject, clazz.getName() + "." + methodName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    return false;
}