Example usage for java.lang.reflect Modifier isPublic

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

Introduction

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

Prototype

public static boolean isPublic(int mod) 

Source Link

Document

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

Usage

From source file:com.comphenix.noxp.FieldUtils.java

/**
 * Gets an accessible <code>Field</code> by name breaking scope if
 * requested. Superclasses/interfaces will be considered.
 * /*from  w ww .j  ava2  s. c  om*/
 * @param cls the class to reflect, must not be null
 * @param fieldName the field name to obtain
 * @param forceAccess whether to break scope restrictions using the
 *            <code>setAccessible</code> method. <code>False</code> will
 *            only match public fields.
 * @return the Field object
 * @throws IllegalArgumentException if the class or field name is null
 */
public static Field getField(final Class cls, String fieldName, boolean forceAccess) {
    if (cls == null) {
        throw new IllegalArgumentException("The class must not be null");
    }
    if (fieldName == null) {
        throw new IllegalArgumentException("The field name must not be null");
    }
    // Sun Java 1.3 has a bugged implementation of getField hence we write
    // the
    // code ourselves

    // getField() will return the Field object with the declaring class
    // set correctly to the class that declares the field. Thus requesting
    // the
    // field on a subclass will return the field from the superclass.
    //
    // priority order for lookup:
    // searchclass private/protected/package/public
    // superclass protected/package/public
    // private/different package blocks access to further superclasses
    // implementedinterface public

    // check up the superclass hierarchy
    for (Class acls = cls; acls != null; acls = acls.getSuperclass()) {
        try {
            Field field = acls.getDeclaredField(fieldName);
            // getDeclaredField checks for non-public scopes as well
            // and it returns accurate results
            if (!Modifier.isPublic(field.getModifiers())) {
                if (forceAccess) {
                    field.setAccessible(true);
                } else {
                    continue;
                }
            }
            return field;
        } catch (NoSuchFieldException ex) {
            // ignore
        }
    }
    // check the public interface case. This must be manually searched for
    // incase there is a public supersuperclass field hidden by a
    // private/package
    // superclass field.
    Field match = null;
    for (Iterator intf = ClassUtils.getAllInterfaces(cls).iterator(); intf.hasNext();) {
        try {
            Field test = ((Class) intf.next()).getField(fieldName);
            if (match != null) {
                throw new IllegalArgumentException(
                        "Reference to field " + fieldName + " is ambiguous relative to " + cls
                                + "; a matching field exists on two or more implemented interfaces.");
            }
            match = test;
        } catch (NoSuchFieldException ex) {
            // ignore
        }
    }
    return match;
}

From source file:org.apache.flink.api.java.typeutils.PojoTypeInfo.java

@PublicEvolving
public PojoTypeInfo(Class<T> typeClass, List<PojoField> fields) {
    super(typeClass);

    checkArgument(Modifier.isPublic(typeClass.getModifiers()), "POJO %s is not public", typeClass);

    this.fields = fields.toArray(new PojoField[fields.size()]);

    Arrays.sort(this.fields, new Comparator<PojoField>() {
        @Override/*from w ww.j  a  v a 2  s  .  co  m*/
        public int compare(PojoField o1, PojoField o2) {
            return o1.getField().getName().compareTo(o2.getField().getName());
        }
    });

    int counterFields = 0;

    for (PojoField field : fields) {
        counterFields += field.getTypeInformation().getTotalFields();
    }

    totalFields = counterFields;
}

From source file:org.solmix.runtime.support.spring.AbstractRootBeanDefinitionParser.java

protected void parseAttributes(Element element, ParserContext parserContext, String id,
        RootBeanDefinition beanDefinition) {
    Set<String> props = new HashSet<String>();
    ManagedMap<String, Object> parameters = null;
    for (Method setter : this.type.getMethods()) {
        String name = setter.getName();
        if (name.length() > 3 && name.startsWith("set") && Modifier.isPublic(setter.getModifiers())
                && setter.getParameterTypes().length == 1) {
            Class<?> type = setter.getParameterTypes()[0];
            String property = StringUtils
                    .camelToSplitName(name.substring(3, 4).toLowerCase() + name.substring(4), "-");
            props.add(property);/*from www . j ava  2 s . c o  m*/
            Method getter = null;
            try {
                getter = this.type.getMethod("get" + name.substring(3), new Class<?>[0]);
            } catch (NoSuchMethodException e) {
                try {
                    getter = this.type.getMethod("is" + name.substring(3), new Class<?>[0]);
                } catch (NoSuchMethodException e2) {
                }
            }
            if (getter == null || !Modifier.isPublic(getter.getModifiers())
                    || !type.equals(getter.getReturnType())) {
                continue;
            }
            if ("properties".equals(property)) {
                parameters = parseProperties(element.getChildNodes(), beanDefinition);
            } else if ("arguments".equals(property)) {
                parseArguments(id, element.getChildNodes(), beanDefinition, parserContext);
            } else {
                String value = element.getAttribute(property);
                if (value != null && value.trim().length() > 0) {
                    value = value.trim();
                    parserValue(beanDefinition, property, type, value, parserContext);
                }
            }
        }
    }
    NamedNodeMap attributes = element.getAttributes();
    int len = attributes.getLength();
    for (int i = 0; i < len; i++) {
        Node node = attributes.item(i);
        String name = node.getLocalName();
        if (!props.contains(name)) {
            if (parameters == null) {
                parameters = new ManagedMap<String, Object>();
            }
            String value = node.getNodeValue();
            parameters.put(name, new TypedStringValue(value, String.class));
        }
    }
    if (parameters != null) {
        beanDefinition.getPropertyValues().addPropertyValue("properties", parameters);
    }
}

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

@Test
public void notAllowdModifiers() throws IllegalAccessException {
    Field[] declaredFields = Modifier.class.getDeclaredFields();
    int maxModifierValue = 0;
    for (Field field : declaredFields) {
        int modifiers = field.getModifiers();
        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)
                && field.getType().equals(Integer.TYPE)) {
            try {
                Integer value = (Integer) field.get(Modifier.class);
                maxModifierValue = Math.max(maxModifierValue, value.intValue());
            } catch (IllegalArgumentException e) {
                throw new AssertionError(e);
            }/* w ww. j  av  a  2 s  .c  o m*/
        }
    }
    maxModifierValue = maxModifierValue << 2;
    try {
        memberCriteria.withModifiers(maxModifierValue);
        throw new AssertionError("modifiers are not allowed");
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        assertTrue(message.startsWith("modifiers must be"));
    }
}

From source file:mangotiger.poker.channel.EventChannelImpl.java

static boolean methodMatchesEvent(final Method method, final Class<?> event) {
    return METHOD_NAME.equals(method.getName()) && Modifier.isPublic(method.getModifiers())
            && Void.TYPE.equals(method.getReturnType()) && method.getParameterTypes().length == 1
            && method.getParameterTypes()[0].isAssignableFrom(event);
}

From source file:com.mawujun.utils.bean.BeanUtils.java

/**
 * ????//from w  ww.j  ava 2s . c  o  m
 * null
 * @param source
 * @param target
 * @throws BeansException
 * @throws IntrospectionException
 */
public static void copyExcludeNull(Object source, Object target) throws IntrospectionException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();

    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    if (value == null) {//??
                        continue;
                    }
                    Method writeMethod = targetPd.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(target, value);
                } catch (Throwable ex) {
                    throw new RuntimeException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.alta189.beaker.CommonEventManager.java

/**
 * Registers all the {@link EventHandler}s contained in the
 * Listener//from  w  w w .  java 2 s .c om
 *
 * @param listener registration, not null
 * @param owner owner of the listener, not null
 * @throws com.alta189.beaker.exceptions.EventRegistrationException
 */
@Override
public void registerListener(Listener listener, Named owner) throws EventRegistrationException {
    try {
        Validate.notNull(listener, "Listener cannot be null");
        Validate.notNull(owner, "Owner cannot be null");
        Validate.notNull(owner.getName(), "Owner's name cannot be null");
        Validate.notEmpty(owner.getName(), "Owner's name cannot be empty");

        for (Method method : listener.getClass().getDeclaredMethods()) {
            if (!method.isAnnotationPresent(EventHandler.class)) {
                continue;
            }

            EventHandler handler = method.getAnnotation(EventHandler.class);
            Validate.notNull(handler.ignoreCancelled(), "ignoredCancelled cannot be null");
            Validate.notNull(handler.priority(), "Priority cannot be null");

            if (!Modifier.isPublic(method.getModifiers())) {
                throw new EventRegistrationException("Method has to be public");
            }

            if (Modifier.isStatic(method.getModifiers())) {
                throw new EventRegistrationException("Method cannot be static");
            }

            if (method.getParameterTypes().length != 1) {
                throw new EventRegistrationException("Method cannot have more than one parameter");
            }

            if (!Event.class.isAssignableFrom(method.getParameterTypes()[0])) {
                throw new EventRegistrationException("Method's parameter type has to extend class");
            }

            EventExecutor executor = new AnnotatedEventExecutor(listener, method);
            HandlerRegistration registration = new HandlerRegistration(executor, handler.priority(),
                    handler.ignoreCancelled(), owner);

            List<HandlerRegistration> list = getRegistrationList(
                    (Class<? extends Event>) method.getParameterTypes()[0], true);
            list.add(registration);
            sortList(list);
        }
    } catch (EventRegistrationException e) {
        throw e;
    } catch (Exception e) {
        throw new EventRegistrationException(e);
    }
}

From source file:io.github.huherto.springyRecords.BaseTable.java

public Number insert(R record) {

    Field[] fields = recordClass().getFields();
    String autoIncrementFieldName = null;
    if (autoIncrementField != null)
        autoIncrementFieldName = autoIncrementField.getName();
    Map<String, Object> parameters = new HashMap<String, Object>(fields.length);
    for (Field field : fields) {
        int mod = field.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
            Column col = field.getAnnotation(Column.class);
            if (col != null && !field.getName().equals(autoIncrementFieldName)) {
                Object value;/*from   ww w  . j  a va 2 s  .  co m*/
                try {
                    value = field.get(record);
                    parameters.put(col.name(), value);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    if (autoIncrementField != null)
        return insertCommand.executeAndReturnKey(parameters);
    insertCommand.execute(parameters);
    return null;
}

From source file:jp.go.nict.langrid.testresource.loader.NodeLoader_1_2.java

protected static void addProperties(Class<?> clazz, Set<String> properties, Set<String> tupleProperties) {
    for (Method m : clazz.getDeclaredMethods()) {
        if (m.getParameterTypes().length != 1)
            continue;
        String name = m.getName();
        if (!name.startsWith("set"))
            continue;
        if (!Modifier.isPublic(m.getModifiers()))
            continue;
        String propName = name.substring(3, 4).toLowerCase() + name.substring(4);
        if (m.getParameterTypes()[0].isArray()) {
            tupleProperties.add(propName);
        } else {/* w ww. ja  va  2 s .  c  o m*/
            properties.add(propName);
        }
    }
}

From source file:com.github.jknack.handlebars.context.MemberValueResolver.java

/**
 * True if the member is public.//  w w  w.  j  a  va 2s.c  o m
 *
 * @param member The member object.
 * @return True if the member is public.
 */
protected boolean isPublic(final M member) {
    return Modifier.isPublic(member.getModifiers());
}