Example usage for java.lang.reflect Field getModifiers

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

Introduction

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

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:org.apache.axis2.jaxws.server.endpoint.injection.impl.WebServiceContextInjectorImpl.java

public void injectOnField(Object resource, Object instance, Field field) throws ResourceInjectionException {
    if (instance == null) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot inject Resource on a null Service Instance.");
        }//w  w w. j  av  a2 s  .com
        throw new ResourceInjectionException(Messages.getMessage("WebServiceContextInjectionImplErr1"));
    }
    if (field == null) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot inject WebServiceContext on ServiceInstance Field, field cannot be NULL");
        }
        throw new ResourceInjectionException(Messages.getMessage("WebServiceContextInjectionImplErr3"));
    }
    try {
        if (!Modifier.isPublic(field.getModifiers())) {
            setAccessible(field, true);
        }
        //Inject Resource.
        field.set(instance, resource);
    } catch (IllegalAccessException e) {
        throw new ResourceInjectionException(e);
    }

}

From source file:adalid.core.AbstractArtifact.java

private boolean isNotRestricted(Field field) {
    int modifiers = field.getModifiers();
    return !(Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers));
}

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

/**
 * Recursively determine all declared fields
 * This is required because class.getFields() is not returning fields defined
 * in parent classes.//from ww w. ja  v a 2s . c  o  m
 *
 * @param clazz class to be analyzed
 * @param ignoreDuplicates if true, in case of duplicate field names only the lowest one
 *                            in a hierarchy will be returned; throws an exception otherwise
 * @return list of fields
 */
@PublicEvolving
public static List<Field> getAllDeclaredFields(Class<?> clazz, boolean ignoreDuplicates) {
    List<Field> result = new ArrayList<Field>();
    while (clazz != null) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) {
                continue; // we have no use for transient or static fields
            }
            if (hasFieldWithSameName(field.getName(), result)) {
                if (ignoreDuplicates) {
                    continue;
                } else {
                    throw new InvalidTypesException(
                            "The field " + field + " is already contained in the hierarchy of the " + clazz
                                    + "." + "Please use unique field names through your classes hierarchy");
                }
            }
            result.add(field);
        }
        clazz = clazz.getSuperclass();
    }
    return result;
}

From source file:com.streamsets.datacollector.definition.ConfigDefinitionExtractor.java

private List<ErrorMessage> validate(String configPrefix, Class klass, List<String> stageGroups,
        boolean validateDependencies, boolean isBean, boolean isComplexField, Object contextMsg) {
    List<ErrorMessage> errors = new ArrayList<>();
    boolean noConfigs = true;
    for (Field field : klass.getFields()) {
        if (field.getAnnotation(ConfigDef.class) != null && field.getAnnotation(ConfigDefBean.class) != null) {
            errors.add(new ErrorMessage(DefinitionError.DEF_152, contextMsg, field.getName()));
        } else {//from   ww  w.j  ava  2s  .  com
            if (field.getAnnotation(ConfigDef.class) != null
                    || field.getAnnotation(ConfigDefBean.class) != null) {
                if (Modifier.isStatic(field.getModifiers())) {
                    errors.add(new ErrorMessage(DefinitionError.DEF_151, contextMsg, klass.getSimpleName(),
                            field.getName()));
                }
                if (Modifier.isFinal(field.getModifiers())) {
                    errors.add(new ErrorMessage(DefinitionError.DEF_154, contextMsg, klass.getSimpleName(),
                            field.getName()));
                }
            }
            if (field.getAnnotation(ConfigDef.class) != null) {
                noConfigs = false;
                List<ErrorMessage> subErrors = validateConfigDef(configPrefix, stageGroups, field,
                        isComplexField, Utils.formatL("{} Field='{}'", contextMsg, field.getName()));
                errors.addAll(subErrors);
            } else if (field.getAnnotation(ConfigDefBean.class) != null) {
                noConfigs = false;
                List<ErrorMessage> subErrors = validateConfigDefBean(configPrefix + field.getName() + ".",
                        field, stageGroups, isComplexField,
                        Utils.formatL("{} BeanField='{}'", contextMsg, field.getName()));
                errors.addAll(subErrors);
            }
        }
    }
    if (isBean && noConfigs) {
        errors.add(new ErrorMessage(DefinitionError.DEF_160, contextMsg));
    }
    if (errors.isEmpty() & validateDependencies) {
        errors.addAll(validateDependencies(getConfigDefinitions(configPrefix, klass, stageGroups, contextMsg),
                contextMsg));
    }
    return errors;
}

From source file:com.adobe.cq.wcm.core.components.extension.contentfragment.internal.models.v1.ContentFragmentImplTest.java

@Before
public void setTestFixture() throws NoSuchFieldException, IllegalAccessException {
    cfmLogger = spy(LoggerFactory.getLogger("FakeLogger"));
    Field field = ContentFragmentImpl.class.getDeclaredField("LOG");
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    field.setAccessible(true);//from  w  w w  . j  av a  2s.c  om
    // remove final modifier from field

    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, cfmLogger);
}

From source file:edu.ku.brc.specify.conversion.CollectionInfo.java

@Override
public String toString() {
    // Taken from a web example
    try {/*w  ww.j av  a2s .  co m*/
        String result = "";
        Class<?> cls = this.getClass();
        Field fieldlist[] = cls.getDeclaredFields();
        for (int i = 0; i < fieldlist.length; i++) {
            Field fld = fieldlist[i];
            if (!Modifier.isStatic(fld.getModifiers())) {
                result += fld.getName() + " = " + fld.get(this) + "\n";
            }
        }
        result += "\n";

        return result;

    } catch (Throwable e) {
        e.printStackTrace();
    }
    return super.toString();
}

From source file:adalid.core.Operation.java

private void finaliseFields() {
    String name;/*  w w w . j a v  a  2s .co  m*/
    Class<?> type;
    int modifiers;
    boolean restricted;
    Class<?>[] classes = new Class<?>[] { Parameter.class, Expression.class };
    Object o;
    int depth = depth();
    int round = round();
    for (Class<?> c : classes) {
        for (Field field : XS1.getFields(getClass(), Operation.class)) { // getClass().getDeclaredFields()
            field.setAccessible(true);
            logger.trace(field);
            name = field.getName();
            type = field.getType();
            if (!c.isAssignableFrom(type)) {
                continue;
            }
            modifiers = field.getModifiers();
            restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
            if (restricted) {
                continue;
            }
            String errmsg = "failed to initialize field \"" + field + "\" at " + this;
            try {
                o = field.get(this);
                if (o == null) {
                    logger.debug(message(type, name, o, depth, round));
                } else if (o instanceof Parameter) {
                    finaliseParameter(field, (Parameter) o);
                } else if (o instanceof Expression) {
                    finaliseExpression(field, (Expression) o);
                }
            } catch (IllegalArgumentException | IllegalAccessException ex) {
                logger.error(errmsg, ThrowableUtils.getCause(ex));
                TLC.getProject().getParser().increaseErrorCount();
            }
        }
    }
}

From source file:mil.army.usace.data.dataquery.rdbms.RdbmsDataQuery.java

private HashMap<Field, String> getDbStructFieldMapping(Class dbStructClazz) {
    HashMap<Field, String> fieldMapping = new HashMap<>();
    Field[] fields = dbStructClazz.getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) { //exclude static fields
            if (field.getAnnotation(Transient.class) == null) {
                fieldMapping.put(field, getDbName(field));
            }//ww  w. j  a v  a 2 s.co  m
        }
    }
    return fieldMapping;
}

From source file:be.fedict.eid.applet.maven.DocbookMojo.java

private void describeClass(Class<?> catalogClass, PrintWriter writer)
        throws IllegalArgumentException, IllegalAccessException {
    writer.println("<section id=\"" + catalogClass.getSimpleName() + "\">");
    writer.println("<title>" + catalogClass.getSimpleName() + "</title>");

    StartRequestMessage startRequestMessage = catalogClass.getAnnotation(StartRequestMessage.class);
    if (null != startRequestMessage) {
        writer.println("<para>");
        writer.println(/*  ww w  . jav  a2  s. c  om*/
                "This message starts a communication session between eID Applet and eID Applet Service.");
        writer.println("It sets the protocol state to: " + startRequestMessage.value());
        writer.println("</para>");
    }

    StopResponseMessage stopResponseMessage = catalogClass.getAnnotation(StopResponseMessage.class);
    if (null != stopResponseMessage) {
        writer.println("<para>");
        writer.println(
                "This message stops a communication session between eID Applet and the eID Applet Service.");
        writer.println("</para>");
    }

    ProtocolStateAllowed protocolStateAllowed = catalogClass.getAnnotation(ProtocolStateAllowed.class);
    if (null != protocolStateAllowed) {
        writer.println("<para>");
        writer.println("This message is only accepted if the eID Applet Service protocol state is: "
                + protocolStateAllowed.value());
        writer.println("</para>");
    }

    Field bodyField = null;

    writer.println("<table>");
    writer.println("<title>" + catalogClass.getSimpleName() + " HTTP headers</title>");
    writer.println("<tgroup cols=\"3\">");
    {
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<colspec colwidth=\"1*\" />");
        writer.println("<colspec colwidth=\"2*\" />");
        writer.println("<thead>");
        writer.println("<row>");
        writer.println("<entry>Header name</entry>");
        writer.println("<entry>Required</entry>");
        writer.println("<entry>Value</entry>");
        writer.println("</row>");
        writer.println("</thead>");
        writer.println("<tbody>");
        {
            Field[] fields = catalogClass.getFields();
            for (Field field : fields) {
                if (field.getAnnotation(HttpBody.class) != null) {
                    bodyField = field;
                }
                HttpHeader httpHeaderAnnotation = field.getAnnotation(HttpHeader.class);
                if (null == httpHeaderAnnotation) {
                    continue;
                }
                writer.println("<row>");
                writer.println("<entry>");
                writer.println("<code>" + httpHeaderAnnotation.value() + "</code>");
                writer.println("</entry>");
                writer.println("<entry>");
                writer.println((null != field.getAnnotation(NotNull.class))
                        || (0 != (field.getModifiers() & Modifier.FINAL)));
                writer.println("</entry>");
                writer.println("<entry>");
                if (0 != (field.getModifiers() & Modifier.FINAL)) {
                    Object value = field.get(null);
                    writer.println("<code>" + value.toString() + "</code>");
                } else {
                    writer.println("Some " + field.getType().getSimpleName() + " value.");
                }
                writer.println("</entry>");
                writer.println("</row>");
            }
        }
        writer.println("</tbody>");
    }
    writer.println("</tgroup>");
    writer.println("</table>");

    if (null != bodyField) {
        writer.println("<para>HTTP body should contain the data.</para>");
        Description description = bodyField.getAnnotation(Description.class);
        if (null != description) {
            writer.println("<para>Body content: ");
            writer.println(description.value());
            writer.println("</para>");
        }
    }

    ResponsesAllowed responsesAllowedAnnotation = catalogClass.getAnnotation(ResponsesAllowed.class);
    if (null != responsesAllowedAnnotation) {
        Class<?>[] responsesAllowed = responsesAllowedAnnotation.value();
        writer.println("<para>");
        writer.println("Allowed eID Applet Service response messages are: ");
        for (Class<?> responseAllowed : responsesAllowed) {
            writer.println("<xref linkend=\"" + responseAllowed.getSimpleName() + "\"/>");
        }
        writer.println("</para>");
    }

    StateTransition stateTransition = catalogClass.getAnnotation(StateTransition.class);
    if (null != stateTransition) {
        writer.println("<para>");
        writer.println("This message will perform an eID Applet protocol state transition to: "
                + stateTransition.value());
        writer.println("</para>");
    }

    writer.println("</section>");
}