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:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java

@Override
public NBTTagCompound toNBT(MBT mbt, Object t) {
    NBTTagCompound nbt = new NBTTagCompound();
    Class clazz = t.getClass();// ww w .j a va 2s .co m
    if (encodeClass)
        nbt.setString(CLASS, clazz.getName());
    while (clazz != null && clazz != Object.class) {
        if (!clazz.isAnnotationPresent(MBTIgnore.class)) {
            for (Field field : clazz.getDeclaredFields()) {
                if (!field.isAnnotationPresent(MBTIgnore.class)) {
                    field.setAccessible(true);
                    if ((encodeFinal || !Modifier.isFinal(field.getModifiers()))
                            && (encodeStatic || !Modifier.isStatic(field.getModifiers()))) {
                        try {
                            nbt.setTag(field.getName(), mbt.toNBT(field.get(t)));
                        } catch (IllegalArgumentException e) {
                            Throwables.propagate(e);
                        } catch (IllegalAccessException e) {
                            Throwables.propagate(e);
                        }
                    }
                }
            }
        }
        clazz = encodeSuper ? clazz.getSuperclass() : Object.class;
    }
    return nbt;
}

From source file:AccessibleFieldIterator.java

protected void addMoreFields() {
    boolean needMoreFields = true;
    while (needMoreFields) {

        for (Field field : this.currentClass.getDeclaredFields()) {

            if (!(field.isSynthetic() || Modifier.isPrivate(field.getModifiers())
                    || this.visibleFieldNames.contains(field.getName()))) {
                try {
                    field.setAccessible(true);
                    this.fieldQueueIterator.add(field);
                    this.visibleFieldNames.add(field.getName());
                    needMoreFields = false;
                } catch (SecurityException e) {
                    // ignore fields that cannot be set accessible
                }/*from ww w  .jav a  2  s. c o m*/
            }
        }

        if (needMoreFields) {
            // found no accessible fields in the current class
            this.currentClass = this.currentClass.getSuperclass();
            if (this.currentClass == null) {
                // no more fields
                return;
            }
        }
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.task.boot.sequences.BootSequenceSecurity.java

public void removeEncryptionRestriction() {
    if (!isRestrictedCryptography()) {
        logger.info("Cryptography restrictions removal not needed");
        return;//  ww w . j  a v  a2 s.c o  m
    }
    try {
        /*
         * Do the following, but with reflection to bypass access checks:
         *
         * JceSecurity.isRestricted = false;
         * JceSecurity.defaultPolicy.perms.clear();
         * JceSecurity.defaultPolicy.add(CryptoAllPermission.INSTANCE);
         */
        final Class<?> jceSecurity = Class.forName("javax.crypto.JceSecurity");
        final Class<?> cryptoPermissions = Class.forName("javax.crypto.CryptoPermissions");
        final Class<?> cryptoAllPermission = Class.forName("javax.crypto.CryptoAllPermission");

        final Field isRestrictedField = jceSecurity.getDeclaredField("isRestricted");
        isRestrictedField.setAccessible(true);
        final Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(isRestrictedField, isRestrictedField.getModifiers() & ~Modifier.FINAL);
        isRestrictedField.set(null, false);

        final Field defaultPolicyField = jceSecurity.getDeclaredField("defaultPolicy");
        defaultPolicyField.setAccessible(true);
        final PermissionCollection defaultPolicy = (PermissionCollection) defaultPolicyField.get(null);

        final Field perms = cryptoPermissions.getDeclaredField("perms");
        perms.setAccessible(true);
        ((Map<?, ?>) perms.get(defaultPolicy)).clear();

        final Field instance = cryptoAllPermission.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        defaultPolicy.add((Permission) instance.get(null));

        logger.info("Successfully removed cryptography restrictions");
    } catch (final Exception e) {
        logger.warn("Failed to remove cryptography restrictions", e);
    }
}

From source file:de.javakaffee.web.msm.serializer.xstream.XStreamTranscoderTest.java

private void assertEqualDeclaredFields(final Class<? extends Object> clazz, final Object one,
        final Object another) throws Exception, IllegalAccessException {
    for (final Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);//from  w w w .  j  a v  a2 s.c o  m
        if (!Modifier.isTransient(field.getModifiers())) {
            assertEquals(field.get(one), field.get(another));
        }
    }
}

From source file:org.openmrs.web.controller.report.ReportObjectFormController.java

@SuppressWarnings("unchecked")
@Override//from  w w w  . jav  a 2s. com
protected Map referenceData(HttpServletRequest request, Object obj, Errors err) throws Exception {
    Map addedData = new HashMap();

    ReportObjectService rs = (ReportObjectService) Context.getService(ReportObjectService.class);

    List<String> availableTypes = rs.getReportObjectTypes();
    addedData.put("availableTypes", availableTypes.iterator());

    String selectedType = ServletRequestUtils.getStringParameter(request, "type", "");

    if (selectedType.length() > 0) {
        List<String> availableSubTypes = rs.getReportObjectSubTypes(selectedType);
        addedData.put("availableSubTypes", availableSubTypes.iterator());
    }

    Map extendedObjectInfo = new HashMap();
    Map transientObjects = new HashMap();
    for (Field field : obj.getClass().getDeclaredFields()) {
        String fieldName = field.getName();
        int modifiers = field.getModifiers();
        if ((modifiers & (0x0 | Modifier.TRANSIENT)) == (0x0 | Modifier.TRANSIENT)) {
            log.debug("OBJECT IS TRANSIENT, SO NOT TRYING TO EDIT");
            transientObjects.put(fieldName, "true");
        } else {
            Method m = obj.getClass().getMethod(
                    "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), (Class[]) null);
            Object fieldObj = m.invoke(obj, (Object[]) null);
            extendedObjectInfo.put(fieldName, fieldObj);
        }

    }
    addedData.put("extendedObjectInfo", extendedObjectInfo);
    addedData.put("transientObjects", transientObjects);

    return addedData;
}

From source file:com.mollie.api.resource.BaseResource.java

/**
 * Convenience method to copy all public properties from a src object into
 * a dst object of the same type.//from w  ww  .j av a2  s  .  c o  m
 *
 * @param src Source object to copy properties from
 * @param dst Target object
 */
protected void copyInto(T src, T dst) {
    Field[] fromFields = returnedClass().getDeclaredFields();
    Object value = null;

    try {
        for (Field field : fromFields) {
            int modifiers = field.getModifiers();

            if ((modifiers & Modifier.PUBLIC) == Modifier.PUBLIC
                    && (modifiers & Modifier.FINAL) != Modifier.FINAL
                    && (modifiers & Modifier.STATIC) != Modifier.STATIC) {
                value = field.get(src);
                field.set(dst, value);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.happyblueduck.lembas.datastore.LembasEntity.java

/**
 * copies values from  lembasEntity to this entity. skip objectKey from that.
 * @param that/*from  w w  w  . j  a v  a2 s.c om*/
 */
public void copy(LembasEntity that) {

    ArrayList<Field> fields = Lists.newArrayList(that.getClass().getFields());
    for (Field f : fields) {
        try {

            int modifiers = f.getModifiers();
            if (Modifier.isPrivate(modifiers))
                continue;
            if (Modifier.isStatic(modifiers))
                continue;
            if (Modifier.isTransient(modifiers))
                continue;
            if (Modifier.isFinal(modifiers))
                continue;
            if (Modifier.isVolatile(modifiers))
                continue;

            if (f.getName().equalsIgnoreCase(LembasUtil.objectKey))
                continue;

            Object value = f.get(that);
            if (value != null)
                this.setField(f, value);

        } catch (IllegalAccessException exception) {
            exception.printStackTrace();
        }
    }
}

From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java

@Override
public List<OneField> getFields(OneRow onerow) throws Exception {
    userObject = onerow.getData();/*from   ww  w .  java2 s  .c  om*/
    List<OneField> record = new LinkedList<OneField>();

    int currentIdx = 0;
    for (Field field : fields) {
        if (currentIdx == recordkeyIndex) {
            currentIdx += recordkeyAdapter.appendRecordkeyField(record, inputData, onerow);
        }

        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        currentIdx += populateRecord(record, field);
    }

    return record;
}

From source file:de.taimos.dvalin.cloud.aws.AWSClientBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>();
    Class<?> targetClass = clazz;

    do {/*  w w  w .  ja va 2s  .c o m*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(AWSClient.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@AWSClient annotation is not supported on static fields");
                }
                currElements.add(new AWSClientElement(field, null, field.getAnnotation(AWSClient.class)));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(AWSClient.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@AWSClient annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@AWSClient annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new AWSClientElement(method, pd, method.getAnnotation(AWSClient.class)));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:cern.c2mon.shared.common.datatag.address.impl.HardwareAddressImpl.java

/**
 * The two addresses are considered equals if they're of the same type and all their non-static attributes are equal
 *//*from w  ww .  j ava2s .  c  om*/
@Override
public final boolean equals(final Object copy) {

    boolean result = copy != null && copy instanceof HardwareAddress && this.getClass().equals(copy.getClass());

    if (result) {

        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isFinal(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
                    && !Modifier.isTransient(field.getModifiers())) {
                try {

                    if ((field.get(this) != null && field.get(copy) == null)
                            || (field.get(this) == null && field.get(copy) != null)) {
                        result = false;
                    } else if (field.get(this) != null && field.get(copy) != null) {

                        if (field.getType().isArray()) {

                            if (Object[].class.isAssignableFrom(field.getType())) {
                                result = Arrays.equals((Object[]) field.get(this), (Object[]) field.get(copy));
                            } else {
                                result = ArrayUtils.isEquals(field.get(this), field.get(copy));
                            }

                        } else {
                            result = field.get(this).equals(field.get(copy));
                        }
                    }
                } catch (Exception e) {
                    result = false;
                }
            }

            if (!result) {
                break;
            }
        }
    }

    return result;
}