Example usage for java.lang.reflect Field isAccessible

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

Introduction

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

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

private JSONObject fillWithClass(JSONObject json, Class<?> clazz) throws JSONMappingException {
    for (Field field : clazz.getDeclaredFields()) {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { // don't care about transient fields.
            continue;
        }//from  w  ww .  ja  v  a  2s  .  c  om

        String jsonName = field.getName();
        if (jsonName.equals("this$0"))
            continue;

        boolean accessible = field.isAccessible();

        if (!accessible)
            field.setAccessible(true);

        try {
            Object value = field.get(this);
            Object jsonField = toJson(value);
            json.put(jsonName, jsonField);
        } catch (Exception e) {
            throw new JSONMappingException(e);
        }

        if (!accessible)
            field.setAccessible(false);
    }

    return json;
}

From source file:bdi4jade.core.Capability.java

/**
 * Adds by reflection capability components, such as beliefs and plans,
 * according to annotated fields. This method is invoked by for capability
 * class, and all parent classes.//from  www  .j av  a 2 s .  c  o m
 * 
 * @param capabilityClass
 *            the capability class of which fields should me added to this
 *            capability.
 */
protected void addAnnotatedFields(Class<? extends Capability> capabilityClass) {
    for (Field field : capabilityClass.getDeclaredFields()) {
        boolean b = field.isAccessible();
        field.setAccessible(true);
        try {
            if (field.isAnnotationPresent(bdi4jade.annotation.Belief.class)) {
                if (Belief.class.isAssignableFrom(field.getType())) {
                    Belief<?, ?> belief = (Belief<?, ?>) field.get(this);
                    this.getBeliefBase().addBelief(belief);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Belief");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.TransientBelief.class)) {
                bdi4jade.annotation.TransientBelief annotation = field
                        .getAnnotation(bdi4jade.annotation.TransientBelief.class);
                String name = "".equals(annotation.name()) ? field.getName() : annotation.name();
                Object value = field.get(this);
                this.getBeliefBase().addBelief(new TransientBelief(name, value));
            } else if (field.isAnnotationPresent(bdi4jade.annotation.TransientBeliefSet.class)) {
                bdi4jade.annotation.TransientBeliefSet annotation = field
                        .getAnnotation(bdi4jade.annotation.TransientBeliefSet.class);
                String name = "".equals(annotation.name()) ? field.getName() : annotation.name();
                Object value = field.get(this);
                if (Set.class.isAssignableFrom(field.getType())) {
                    this.getBeliefBase().addBelief(new TransientBeliefSet(name, (Set) value));
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.Plan.class)) {
                if (Plan.class.isAssignableFrom(field.getType())) {
                    Plan plan = (Plan) field.get(this);
                    this.getPlanLibrary().addPlan(plan);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Plan");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.AssociatedCapability.class)) {
                if (Capability.class.isAssignableFrom(field.getType())) {
                    Capability capability = (Capability) field.get(this);
                    this.addAssociatedCapability(capability);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Capability");
                }
            } else if (field.isAnnotationPresent(bdi4jade.annotation.PartCapability.class)) {
                if (Capability.class.isAssignableFrom(field.getType())) {
                    Capability capability = (Capability) field.get(this);
                    this.addPartCapability(capability);
                } else {
                    throw new ClassCastException("Field " + field.getName() + " should be a Capability");
                }
            }
        } catch (Exception exc) {
            log.warn(exc);
            exc.printStackTrace();
        }
        field.setAccessible(b);
    }
}

From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java

public void composerInject(final Object target) throws IllegalAccessException {
    WebBeansContext webBeansContext = null;
    try {/*  ww  w  .j  a  va  2 s  .c o  m*/
        webBeansContext = WebBeansContext.currentInstance();
    } catch (final IllegalStateException ise) {
        // no-op
    }
    if (webBeansContext != null) {
        OWBInjector.inject(webBeansContext.getBeanManagerImpl(), target, null);
    }

    Class<?> aClass = target.getClass();
    while (aClass != null && aClass != Object.class) {
        for (final Field f : aClass.getDeclaredFields()) {
            final RandomPort randomPort = f.getAnnotation(RandomPort.class);
            if (randomPort != null) {
                for (final Field field : app.getClass().getDeclaredFields()) {
                    final RandomPort appPort = field.getAnnotation(RandomPort.class);
                    if (field.getType() == f.getType() && appPort != null
                            && appPort.value().equals(randomPort.value())) {
                        if (!field.isAccessible()) {
                            field.setAccessible(true);
                        }
                        if (!f.isAccessible()) {
                            f.setAccessible(true);
                        }

                        final Object value = field.get(app);
                        f.set(target, value);
                        break;
                    }
                }
            } else if (f.isAnnotationPresent(Application.class)) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                f.set(target, app);
            } else if (f.isAnnotationPresent(LifecycleTask.class)) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                final LifecycleTaskAccessor accessor = SystemInstance.get()
                        .getComponent(LifecycleTaskAccessor.class);
                final Class type = f.getType();
                final Object taskByType = accessor.getTaskByType(type);
                f.set(target, taskByType);
            } else if (f.isAnnotationPresent(Args.class)) {
                if (String[].class != f.getType()) {
                    throw new IllegalArgumentException(
                            "@Args can only be used for String[] field, not on " + f.getType());
                }
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }
                final TomEEEmbeddedArgs args = SystemInstance.get().getComponent(TomEEEmbeddedArgs.class);
                f.set(target, args == null ? new String[0] : args.getArgs());
            }
        }
        aClass = aClass.getSuperclass();
    }

    SystemInstance.get().fireEvent(new TomEEEmbeddedApplicationRunnerInjection(target));
}

From source file:com.quancheng.saluki.boot.runner.GrpcReferenceRunner.java

@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    Class<?> searchType = bean.getClass();
    while (!Object.class.equals(searchType) && searchType != null) {
        Field[] fields = searchType.getDeclaredFields();
        for (Field field : fields) {
            SalukiReference reference = field.getAnnotation(SalukiReference.class);
            if (reference != null) {
                Object value = null;
                try {
                    value = applicationContext.getBean(field.getType());
                } catch (NoSuchBeanDefinitionException e) {
                    value = null;// w  ww  .j a v  a2  s .c o m
                }
                if (value == null) {
                    value = refer(reference, field.getType());
                }
                try {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    field.set(bean, value);
                } catch (Throwable e) {
                    logger.error("Failed to init remote service reference at filed " + field.getName()
                            + " in class " + bean.getClass().getName() + ", cause: " + e.getMessage(), e);
                }
            }
        }
        searchType = searchType.getSuperclass();
    }
    return bean;
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private void deserializeClass(Class<?> instanceClass, Object instance) throws SerializationException,
        IllegalAccessException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
    Field[] serializableFields = SerializabilityUtil.applyFieldSerializationPolicy(instanceClass);

    for (Field declField : serializableFields) {
        assert (declField != null);

        Object value = deserializeValue(declField.getType());

        boolean isAccessible = declField.isAccessible();
        boolean needsAccessOverride = !isAccessible && !Modifier.isPublic(declField.getModifiers());
        if (needsAccessOverride) {
            // Override access restrictions
            declField.setAccessible(true);
        }/*from   ww w  .  j a va  2 s .co m*/

        declField.set(instance, value);
    }

    Class<?> superClass = instanceClass.getSuperclass();
    if (serializationPolicy.shouldDeserializeFields(superClass)) {
        deserializeImpl(SerializabilityUtil.hasCustomFieldSerializer(superClass), superClass, instance);
    }
}

From source file:org.apache.sling.oakui.OakUIWebConsole.java

@Nonnull
private NodeStore getNodeStore() {
    try {// w w  w.ja va 2s.  c o m
        // this could be static, but as is doesnt cost much.
        Field managerStore = null;
        try {
            managerStore = slingRepository.getClass().getDeclaredField("manager");
        } catch (NoSuchFieldException e) {
            LOGGER.info("Sling Repository (type {}) does not have a field manager ",
                    slingRepository.getClass());
            throw new RuntimeException("Unable to get the NodeStore from the repository", e);
        }
        if (!managerStore.isAccessible()) {
            managerStore.setAccessible(true);
        }
        // no idea what manager is, so get the class on the fly and find the field
        Object o = managerStore.get(slingRepository);
        Field storeField = null;
        try {
            storeField = o.getClass().getDeclaredField("store");
        } catch (NoSuchFieldException e) {
            LOGGER.info("Sling Repository Manager (type:{}) does not have a field store ", o.getClass());
            throw new RuntimeException("Unable to get the NodeStore from the repository", e);
        }
        if (!storeField.isAccessible()) {
            storeField.setAccessible(true);
        }
        return (NodeStore) storeField.get(o);
    } catch (Exception e) {
        throw new RuntimeException("Unable to get the NodeStore from the repository", e);
    }
}

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

/** Des-serialize a JSON object.
 * @throws JSONException/*  ww  w . ja  va2 s.  c  o m*/
 * @throws JSONMappingException */
public JSONEntity(JSONObject json) throws JSONMappingException {
    if (json == null)
        return;
    Class<?> clazz = this.getClass();
    List<Field> declaredFields = new ArrayList<Field>();
    do {
        Field[] fields = clazz.getDeclaredFields();
        declaredFields.addAll(Arrays.asList(fields));
        clazz = clazz.getSuperclass();
    } while (clazz != null && !clazz.isAssignableFrom(JSONEntity.class));
    for (Field field : declaredFields) {
        if ((field.getModifiers() & Modifier.TRANSIENT) != 0) { // don't care about transient fields.
            continue;
        }

        String fieldName = field.getName();
        if (fieldName.equals("this$0"))
            continue;

        boolean accessible = field.isAccessible();
        if (!accessible)
            field.setAccessible(true);

        Class<?> type = field.getType();

        if (type.isArray()) {
            Class<?> componentClass = type.getComponentType();
            JSONArray jsonArray = null;
            try {
                jsonArray = json.getJSONArray(fieldName);
            } catch (JSONException e) {
                // no data for this field found.
                continue;
            }

            int size = jsonArray.length();

            Object array = Array.newInstance(componentClass, size);
            for (int i = 0; i < size; i++) {
                try {
                    Object item = fromJson(componentClass, jsonArray.get(i));
                    Array.set(array, i, item);
                } catch (Exception e) {
                    System.err.println("Invalid array component for class " + this.getClass().getName()
                            + " field " + field.getName() + "::" + field.getType().getName());
                }
            }

            try {
                field.set(this, array);
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else if (JSONEntity.class.isAssignableFrom(type)) {
            try {
                Object entity = readJSONEntity(type, json.getJSONObject(fieldName));
                field.set(this, entity);
            } catch (JSONException e) {
                // keep going.. the json representation doesn't have value for this field.
            } catch (Exception e) {
                throw new JSONMappingException(e);
            }
        } else {
            FieldSetter setter = JSON_READERS.get(type.getName());
            if (setter != null) {
                try {
                    setter.setField(this, field, json, fieldName);
                } catch (JSONException e) {
                    // do nothing. We just didn't receive data for this field
                } catch (Exception e) {
                    throw new JSONMappingException(e);
                }
            } else {
                Object jsonObj;
                try {
                    jsonObj = json.get(fieldName);
                } catch (Exception e) {
                    jsonObj = null;
                }
                if (jsonObj != null) {
                    Object value = fromJson(type, jsonObj);
                    try {
                        field.set(this, value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.err.println("No setter for " + field);
                }

            }
        }

        if (!accessible)
            field.setAccessible(false);
    }
}

From source file:org.kuali.coeus.common.budget.framework.query.QueryList.java

/**
 * sorts the QueryList by the fieldName in ascending or descending order.
 * Note: the field Object should be of Comparable type.
 * @return boolean indicating whether the sort is completed successfully or not.
 * @param ignoreCase use only when comparing strings. as default implementation uses case sensitive comparison.
 * @param fieldName field which is used to sort the bean.
 * @param ascending if true sorting is done in ascending order,
 * else sorting is done in descending order.
 *///from www  . j av a2s. c  o  m
@SuppressWarnings("rawtypes")
public boolean sort(String fieldName, boolean ascending, boolean ignoreCase) {
    Object current, next;
    int compareValue = 0;
    Field field = null;
    Method method = null;
    if (this.size() == 0) {
        return false;
    }
    Class dataClass = get(0).getClass();
    String methodName = null;
    try {
        field = dataClass.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        //field not available. Use method invokation.
        try {
            methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            method = dataClass.getMethod(methodName, null);
        } catch (NoSuchMethodException noSuchMethodException) {
            LOG.error(noSuchMethodException.getMessage(), noSuchMethodException);
            return false;
        }
    }

    for (int index = 0; index < size() - 1; index++) {
        for (int nextIndex = index + 1; nextIndex < size(); nextIndex++) {
            current = get(index);
            next = get(nextIndex);
            //Check if current and next implements Comparable else can't compare.
            //so return without comparing.May be we can have an exception for this purpose.
            try {
                if (field != null && field.isAccessible()) {
                    Comparable thisObj = (Comparable) field.get(current);
                    Comparable otherObj = (Comparable) field.get(next);
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                } else {
                    Comparable thisObj = null;
                    Comparable otherObj = null;
                    if (methodName != null) {
                        Method thisObjMethod = current.getClass().getMethod(methodName, null);
                        Method otherObjMethod = next.getClass().getMethod(methodName, null);
                        thisObj = (Comparable) thisObjMethod.invoke(current, null);
                        otherObj = (Comparable) otherObjMethod.invoke(next, null);
                    } else {
                        thisObj = (Comparable) method.invoke(current, null);
                        otherObj = (Comparable) method.invoke(next, null);
                    }
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                }
            } catch (IllegalAccessException illegalAccessException) {
                LOG.warn(illegalAccessException.getMessage());
                return false;
            } catch (InvocationTargetException invocationTargetException) {
                LOG.warn(invocationTargetException.getMessage(), invocationTargetException);
                return false;
            } catch (SecurityException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            } catch (NoSuchMethodException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            }

            if (ascending && compareValue > 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            } else if (!ascending && compareValue < 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            }

        }
    }
    return true;
}

From source file:org.kuali.kra.budget.calculator.QueryList.java

/**
 * sorts the QueryList by the fieldName in ascending or descending order.
 * Note: the field Object should be of Comparable type.
 * @return boolean indicating whether the sort is completed successfully or not.
 * @param ignoreCase use only when comparing strings. as default implementation uses case sensitive comparison.
 * @param fieldName field which is used to sort the bean.
 * @param ascending if true sorting is done in ascending order,
 * else sorting is done in descending order.
 *//* w  w w.j  a v a2s  .  c  o m*/
@SuppressWarnings("rawtypes")
public boolean sort(String fieldName, boolean ascending, boolean ignoreCase) {
    Object current, next;
    int compareValue = 0;
    Field field = null;
    Method method = null;
    if (this.size() == 0) {
        return false;
    }
    Class dataClass = get(0).getClass();
    String methodName = null;
    try {
        field = dataClass.getDeclaredField(fieldName);
        if (!field.isAccessible()) {
            throw new NoSuchFieldException();
        }
    } catch (NoSuchFieldException noSuchFieldException) {
        //field not available. Use method invokation.
        try {
            methodName = "get" + (fieldName.charAt(0) + "").toUpperCase() + fieldName.substring(1);
            method = dataClass.getMethod(methodName, null);
        } catch (NoSuchMethodException noSuchMethodException) {
            noSuchMethodException.printStackTrace();
            return false;
        }
    }

    for (int index = 0; index < size() - 1; index++) {
        for (int nextIndex = index + 1; nextIndex < size(); nextIndex++) {
            current = get(index);
            next = get(nextIndex);
            //Check if current and next implements Comparable else can't compare.
            //so return without comparing.May be we can have an exception for this purpose.
            try {
                if (field != null && field.isAccessible()) {
                    Comparable thisObj = (Comparable) field.get(current);
                    Comparable otherObj = (Comparable) field.get(next);
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                } else {
                    Comparable thisObj = null;
                    Comparable otherObj = null;
                    if (methodName != null) {
                        Method thisObjMethod = current.getClass().getMethod(methodName, null);
                        Method otherObjMethod = next.getClass().getMethod(methodName, null);
                        thisObj = (Comparable) thisObjMethod.invoke(current, null);
                        otherObj = (Comparable) otherObjMethod.invoke(next, null);
                    } else {
                        thisObj = (Comparable) method.invoke(current, null);
                        otherObj = (Comparable) method.invoke(next, null);
                    }
                    if (thisObj == null) {
                        compareValue = -1;
                    } else if (otherObj == null) {
                        compareValue = 1;
                    } else {
                        if (thisObj instanceof String && ignoreCase) {
                            compareValue = ((String) thisObj).compareToIgnoreCase((String) otherObj);
                        } else {
                            compareValue = thisObj.compareTo(otherObj);
                        }
                    }
                }
            } catch (IllegalAccessException illegalAccessException) {
                LOG.warn(illegalAccessException.getMessage());
                return false;
            } catch (InvocationTargetException invocationTargetException) {
                LOG.warn(invocationTargetException.getMessage(), invocationTargetException);
                return false;
            } catch (SecurityException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            } catch (NoSuchMethodException e) {
                LOG.warn(e.getMessage(), e);
                return false;
            }

            if (ascending && compareValue > 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            } else if (!ascending && compareValue < 0) {
                E temp = get(index);
                set(index, get(nextIndex));
                set(nextIndex, temp);
            }

        }
    }
    return true;
}