Example usage for java.lang.reflect Modifier isPrivate

List of usage examples for java.lang.reflect Modifier isPrivate

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPrivate.

Prototype

public static boolean isPrivate(int mod) 

Source Link

Document

Return true if the integer argument includes the private modifier, false otherwise.

Usage

From source file:hu.bme.mit.sette.common.model.snippet.SnippetContainer.java

/**
 * Validates methods of the class.//w  w  w  .  j ava  2s. c  om
 *
 * @param validator
 *            a validator
 * @return a map containing the snippet methods by their name
 */
private Map<String, Method> validateMethods(final AbstractValidator<?> validator) {
    // check: only "[public|private] static" or synthetic methods
    Map<String, Method> snippetMethods = new HashMap<String, Method>();

    for (Method method : javaClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            // skip synthetic methods
            continue;
        }

        MethodValidator v = new MethodValidator(method);

        if (snippetMethods.get(method.getName()) != null) {
            v.addException("The method must have a unique name");
        }

        int methodModifiers = method.getModifiers();

        if (!Modifier.isPublic(methodModifiers) && !Modifier.isPrivate(methodModifiers)) {
            v.addException("The method must be public or private");
        }

        v.withModifiers(Modifier.STATIC);
        v.withoutModifiers(Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE | Modifier.SYNCHRONIZED);

        AnnotationMap methodAnns = SetteAnnotationUtils.getSetteAnnotations(method);

        if (Modifier.isPublic(methodModifiers)) {
            if (methodAnns.get(SetteNotSnippet.class) == null) {
                // should be snippet, validated by Snippet class and added
                // later
                snippetMethods.put(method.getName(), method);
            } else {
                // not snippet
                snippetMethods.put(method.getName(), null);

                if (methodAnns.size() != 1) {
                    v.addException("The method must not have " + "any other SETTE annotations "
                            + "if it is not a snippet.");
                }
            }
        } else {
            // method is private
            if (methodAnns.size() != 0) {
                v.addException("The method must not have " + "any SETTE annotations");
            }
        }

        validator.addChildIfInvalid(v);
    }

    return snippetMethods;
}

From source file:com.stratio.es.utils.UtilESTest.java

@Test(expectedExceptions = InvocationTargetException.class)
public void testConstructorIsPrivate() throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    Constructor<UtilES> constructor = UtilES.class.getDeclaredConstructor();
    assertTrue(Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);//from www  .  j  a v a 2s . c o m
    constructor.newInstance();
}

From source file:org.springframework.aop.framework.CglibAopProxy.java

/**
 * Checks for final methods on the given {@code Class}, as well as package-visible
 * methods across ClassLoaders, and writes warnings to the log for each one found.
 *///from  www  .  jav a  2s .c o  m
private void doValidateClass(Class<?> proxySuperClass, @Nullable ClassLoader proxyClassLoader,
        Set<Class<?>> ifcs) {
    if (proxySuperClass != Object.class) {
        Method[] methods = proxySuperClass.getDeclaredMethods();
        for (Method method : methods) {
            int mod = method.getModifiers();
            if (!Modifier.isStatic(mod) && !Modifier.isPrivate(mod)) {
                if (Modifier.isFinal(mod)) {
                    if (implementsInterface(method, ifcs)) {
                        logger.warn("Unable to proxy interface-implementing method [" + method + "] because "
                                + "it is marked as final: Consider using interface-based JDK proxies instead!");
                    }
                    logger.info("Final method [" + method + "] cannot get proxied via CGLIB: "
                            + "Calls to this method will NOT be routed to the target instance and "
                            + "might lead to NPEs against uninitialized fields in the proxy instance.");
                } else if (!Modifier.isPublic(mod) && !Modifier.isProtected(mod) && proxyClassLoader != null
                        && proxySuperClass.getClassLoader() != proxyClassLoader) {
                    logger.info("Method [" + method + "] is package-visible across different ClassLoaders "
                            + "and cannot get proxied via CGLIB: Declare this method as public or protected "
                            + "if you need to support invocations through the proxy.");
                }
            }
        }
        doValidateClass(proxySuperClass.getSuperclass(), proxyClassLoader, ifcs);
    }
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteriaTest.java

@Test
public void privateStaticFields() {
    memberCriteria.membersOfType(Field.class);
    memberCriteria.withAccess(AccessType.PRIVATE);
    memberCriteria.withModifiers(Modifier.STATIC);
    ClassCriteria classCriteria = new ClassCriteria();
    Iterable<Class<?>> classIterable = classCriteria.getIterable(Class.class);
    Iterable<Member> memberIterable = memberCriteria.getIterable(classIterable);
    assertTrue(memberIterable.iterator().hasNext());
    for (Member member : memberIterable) {
        assertTrue("member must be a field", member instanceof Field);
        int modifiers = member.getModifiers();
        assertFalse(Modifier.isPublic(modifiers));
        assertFalse(Modifier.isProtected(modifiers));
        assertTrue(Modifier.isPrivate(modifiers));
        assertTrue(Modifier.isStatic(modifiers));
    }//from   www .j a  va2 s.  c  om
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

/**
 * Get the method with the given name from the given class, provided that it takes one argument
 * of the provided type.//from  w  w  w. java2s.c  o m
 * @param cls The class who should have (or inherit) the method
 * @param methodName The name of the method
 * @param argClass If provided, the type of the sole argument to the method. If null, no argument is assumed.
 * @param onlyProtectedAndHigher If true, we will ignore private methods in the superclasses.
 * @return The method if found, otherwise null.
 */
private static Method getMethodFromClass(Class<?> cls, String methodName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {

    Method[] allMethods = cls.getDeclaredMethods();
    for (Method meth : allMethods) {
        if (!meth.getName().equals(methodName))
            continue;

        if (onlyProtectedAndHigher) {
            int modifiers = meth.getModifiers();
            if (Modifier.isPrivate(modifiers))
                continue;
        }

        if (argClass != null) {
            Class<?>[] paramTypes = meth.getParameterTypes();
            if (paramTypes.length != 1)
                continue;

            Class<?> genericType = getGenericType(paramTypes[0]);
            if (!genericType.isAssignableFrom(argClass))
                continue;
        }

        // Note that if we're trying to set a value to null, we obviously cannot check the
        // signature for overloading, and therefore we'll return the first method which takes
        // one parameter. I think that's not that unreasonable, but it could conceivably break
        // if someone does funny things with their bean.

        return meth;
    }

    return null;
}

From source file:edu.utah.further.fqe.impl.service.query.AggregationServiceImpl.java

/**
 * @param federatedQueryContext/*from www .  j av  a2s  . com*/
 * @return
 * @see edu.utah.further.fqe.api.service.query.AggregationService#generatedAggregatedResults(edu.utah.further.fqe.ds.api.domain.QueryContext)
 */
@Override
public synchronized AggregatedResults generateAggregatedResults(final QueryContext federatedQueryContext) {
    final QueryContext parent = qcService.findById(federatedQueryContext.getId());

    if (parent.getQueryType() == QueryType.COUNT_QUERY) {
        throw new ApplicationException("Data cannot be aggregated for count-only queries");
    }

    final List<QueryContext> children = qcService.findChildren(parent);

    if (children.size() < 1) {
        throw new ApplicationException("Federated QueryContext does not have any children");
    }

    final List<String> queryIds = new ArrayList<>();

    for (final QueryContext childContext : children) {
        if (childContext.isFailed()) {
            throw new ApplicationException(
                    "One or more queries failed, aggregated results cannot be generated");
        }

        queryIds.add(childContext.getExecutionId());
    }

    final Class<?> rootResultClass = resultDataService.getRootResultClass(queryIds);

    // Sanity check
    Validate.isTrue(PersistentEntity.class.isAssignableFrom(rootResultClass));

    final List<String> fields = new ArrayList<>();
    final Set<String> aggregationIncludedFields = categories.keySet();
    for (final Field field : rootResultClass.getDeclaredFields()) {
        // Only consider private and non-excluded fields
        if (Modifier.isPrivate(field.getModifiers()) && aggregationIncludedFields.contains(field.getName())) {
            fields.add(field.getName());
        }
    }

    final AggregatedResults aggregatedResults = new AggregatedResultsTo();

    // get all virtual ids for intersection
    final Map<Long, Set<Long>> commonToVirtualMap = identifierService.getCommonIdToVirtualIdMap(queryIds, true);
    final List<Long> idsInIntersection = CollectionUtil.newList();
    for (final Set<Long> virtuals : commonToVirtualMap.values()) {
        // Add the first virtual id, ignore all the others and make very big
        // assumption
        // that because they're the same person, they'll also have the same record
        // information
        idsInIntersection.add(virtuals.iterator().next());
    }

    if (queryIds.size() > 1) {
        // get all virtual ids for sum
        final List<Long> idsInSum = identifierService.getVirtualIdentifiers(queryIds);
        final AggregatedResult aggregatedSum = generateAggregatedResult(fields,
                rootResultClass.getCanonicalName(), queryIds, idsInSum, ResultType.SUM);
        aggregatedResults.addResult(aggregatedSum);

        final AggregatedResult aggregatedIntersection = generateAggregatedResult(fields,
                rootResultClass.getCanonicalName(), queryIds, idsInIntersection, ResultType.INTERSECTION);
        aggregatedResults.addResult(aggregatedIntersection);
    }

    // get all virtual ids for union
    final List<Long> idsInUnion = new ArrayList<>();
    idsInUnion.addAll(identifierService.getUnresolvedVirtualIdentifiers(queryIds));
    idsInUnion.addAll(idsInIntersection);

    final AggregatedResult aggregatedUnion = generateAggregatedResult(fields,
            rootResultClass.getCanonicalName(), queryIds, idsInUnion, ResultType.UNION);
    aggregatedResults.addResult(aggregatedUnion);

    aggregatedResults.setNumDataSources(queryIds.size());

    return aggregatedResults;
}

From source file:io.github.eternalbits.compactvd.CompactVD.java

private static void dump(Object obj, String in) {
    for (Field fld : obj.getClass().getDeclaredFields()) {
        try {/*w ww  . j av  a2  s.  c  om*/
            if (!Modifier.isPrivate(fld.getModifiers())) {
                if (fld.getAnnotation(Deprecated.class) == null) {
                    if (!fld.getType().isAssignableFrom(List.class)) {
                        System.out.println(in + fld.getName() + ": " + fld.get(obj));
                    } else {
                        int i = 0;
                        for (Object item : (List<?>) fld.get(obj)) {
                            System.out.println(in + fld.getName() + "[" + i + "]");
                            dump(item, in + "    ");
                            i++;
                        }
                    }
                }
            }
        } catch (IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteriaTest.java

@Test
public void protecedConstructors() {
    memberCriteria.membersOfType(Constructor.class);
    memberCriteria.withAccess(AccessType.PROTECTED);
    ClassCriteria classCriteria = new ClassCriteria();
    Iterable<Class<?>> classIterable = classCriteria.getIterable(ArrayList.class);
    Iterable<Member> memberIterable = memberCriteria.getIterable(classIterable);
    assertTrue(memberIterable.iterator().hasNext());
    for (Member member : memberIterable) {
        assertTrue("member must be a constructor", member instanceof Constructor<?>);
        int modifiers = member.getModifiers();
        assertFalse(Modifier.isPublic(modifiers));
        assertTrue(Modifier.isProtected(modifiers));
        assertFalse(Modifier.isPrivate(modifiers));
    }/*from w ww  . j a va 2s  .  co  m*/
}

From source file:org.apache.felix.webconsole.AbstractWebConsolePlugin.java

/**
 * Returns a method which is called on the
 * {@link #getResourceProvider() resource provider} class to return an URL
 * to a resource which may be spooled when requested. The method has the
 * following signature:/*from   w w w  .ja va2s  .  c om*/
 * <pre>
 * [modifier] URL getResource(String path);
 * </pre>
 * Where the <i>[modifier]</i> may be <code>public</code>, <code>protected</code>
 * or <code>private</code> (if the method is declared in the class of the
 * resource provider). It is suggested to use the <code>private</code>
 * modifier if the method is declared in the resource provider class or
 * the <code>protected</code> modifier if the method is declared in a
 * base class of the resource provider.
 *
 * @return The <code>getResource(String)</code> method or <code>null</code>
 *      if the {@link #getResourceProvider() resource provider} is
 *      <code>null</code> or does not provide such a method.
 */
private final Method getGetResourceMethod() {
    // return what we know of the getResourceMethod, if we already checked
    if (getResourceMethodChecked) {
        return getResourceMethod;
    }

    Method tmpGetResourceMethod = null;
    Object resourceProvider = getResourceProvider();
    if (resourceProvider != null) {
        try {
            Class cl = resourceProvider.getClass();
            while (tmpGetResourceMethod == null && cl != Object.class) {
                Method[] methods = cl.getDeclaredMethods();
                for (int i = 0; i < methods.length; i++) {
                    Method m = methods[i];
                    if (GET_RESOURCE_METHOD_NAME.equals(m.getName()) && m.getParameterTypes().length == 1
                            && m.getParameterTypes()[0] == String.class && m.getReturnType() == URL.class) {
                        // ensure modifier is protected or public or the private
                        // method is defined in the plugin class itself
                        int mod = m.getModifiers();
                        if (Modifier.isProtected(mod) || Modifier.isPublic(mod)
                                || (Modifier.isPrivate(mod) && cl == resourceProvider.getClass())) {
                            m.setAccessible(true);
                            tmpGetResourceMethod = m;
                            break;
                        }
                    }
                }
                cl = cl.getSuperclass();
            }
        } catch (Throwable t) {
            tmpGetResourceMethod = null;
        }
    }

    // set what we have found and prevent future lookups
    getResourceMethod = tmpGetResourceMethod;
    getResourceMethodChecked = true;

    // now also return the method
    return getResourceMethod;
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteria.java

/**
 * Set the criterion that selects only {@link Member}s that exactly have the
 * specified modifiers. The access modifiers are set separately. Use
 * {@link #withAccess(AccessType...)} to set access modifiers.
 *
 * @param modifiers//from w  w w. j a v a  2  s  .co m
 * @since 1.0.0.0
 */
public void withModifiers(int modifiers) {
    if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers)) {
        throw new IllegalArgumentException(
                "access modifiers are not allowed as argument. Use withAccess() instead.");
    }
    int allowedModifiers = Modifier.ABSTRACT | Modifier.STATIC | Modifier.FINAL | Modifier.TRANSIENT
            | Modifier.VOLATILE | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.STRICT
            | Modifier.INTERFACE;

    if ((modifiers & allowedModifiers) == 0) {
        throw new IllegalArgumentException(
                "modifiers must be one of [" + Modifier.toString(allowedModifiers) + "]");
    }

    this.modifiers = modifiers;
}