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:com.alibaba.dubbo.config.spring.AnnotationBean.java

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    if (!isMatchPackage(bean)) {
        return bean;
    }/*from   w ww .  j ava2  s  .c  o  m*/
    Method[] methods = bean.getClass().getMethods();
    for (Method method : methods) {
        String name = method.getName();
        if (name.length() > 3 && name.startsWith("set") && method.getParameterTypes().length == 1
                && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())) {
            try {
                Reference reference = method.getAnnotation(Reference.class);
                if (reference != null) {
                    Object value = refer(reference, method.getParameterTypes()[0]);
                    if (value != null) {
                        method.invoke(bean, new Object[] {});
                    }
                }
            } catch (Throwable e) {
                logger.error("Failed to init remote service reference at method " + name + " in class "
                        + bean.getClass().getName() + ", cause: " + e.getMessage(), e);
            }
        }
    }
    Field[] fields = bean.getClass().getDeclaredFields();
    for (Field field : fields) {
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            Reference reference = field.getAnnotation(Reference.class);
            if (reference != null) {
                Object value = refer(reference, field.getType());
                if (value != null) {
                    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);
        }
    }
    return bean;
}

From source file:com.github.srgg.springmockito.MockitoPropagatingFactoryPostProcessor.java

@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    final Map<Field, Object> fields = new LinkedHashMap();

    for (Object c : contexts) {
        for (Field f : FieldUtils.getAllFields(c.getClass())) {
            if (f.isAnnotationPresent(Mock.class) || f.isAnnotationPresent(Spy.class)
                    || includeInjectMocks && f.isAnnotationPresent(InjectMocks.class)) {
                try {
                    if (!f.isAccessible()) {
                        f.setAccessible(true);
                    }/*from  w ww  .  ja  va 2s.  c om*/

                    Object o = f.get(c);

                    fields.put(f, o);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    for (final Map.Entry<Field, Object> e : fields.entrySet()) {
        final Field f = e.getKey();

        /*
         * To be processed by BeanPostProcessors, value must be an instance of FactoryBean
         */
        final FactoryBean fb = new SimpleHolderFactoryBean(e.getValue());
        beanFactory.registerSingleton(f.getName(), fb);
    }
}

From source file:org.silverpeas.servlet.RequestParameterDecoder.java

/**
 * The private implementation./*w  ww.j  ava 2s. c  om*/
 */
private <OBJECT> OBJECT _decode(HttpRequest request, Class<OBJECT> objectClass) {
    try {

        // New instance
        OBJECT newInstance = objectClass.newInstance();

        // Reading all class fields.
        for (Field field : objectClass.getDeclaredFields()) {
            // Is existing the FormParam annotation ?
            FormParam param = field.getAnnotation(FormParam.class);
            if (param != null) {
                boolean isAccessible = field.isAccessible();
                if (!isAccessible) {
                    field.setAccessible(true);
                }
                field.set(newInstance,
                        getParameterValue(request,
                                StringUtil.isDefined(param.value()) ? param.value() : field.getName(),
                                field.getType()));
                if (!isAccessible) {
                    field.setAccessible(false);
                }
            }
        }

        // Instance is set.
        // Returning it.
        return newInstance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

private static Object getEmptyObject(Class<?> returnType, Map<Class<?>, Object> emptyInstances, int level) {
    if (level > 2)
        return null;
    if (returnType == null) {
        return null;
    } else if (returnType == boolean.class || returnType == Boolean.class) {
        return false;
    } else if (returnType == char.class || returnType == Character.class) {
        return '\0';
    } else if (returnType == byte.class || returnType == Byte.class) {
        return (byte) 0;
    } else if (returnType == short.class || returnType == Short.class) {
        return (short) 0;
    } else if (returnType == int.class || returnType == Integer.class) {
        return 0;
    } else if (returnType == long.class || returnType == Long.class) {
        return 0L;
    } else if (returnType == float.class || returnType == Float.class) {
        return 0F;
    } else if (returnType == double.class || returnType == Double.class) {
        return 0D;
    } else if (returnType.isArray()) {
        return Array.newInstance(returnType.getComponentType(), 0);
    } else if (returnType.isAssignableFrom(ArrayList.class)) {
        return new java.util.ArrayList<Object>(0);
    } else if (returnType.isAssignableFrom(HashSet.class)) {
        return new HashSet<Object>(0);
    } else if (returnType.isAssignableFrom(HashMap.class)) {
        return new java.util.concurrent.ConcurrentHashMap<Object, Object>(0);
    } else if (String.class.equals(returnType)) {
        return "";
    } else if (!returnType.isInterface()) {
        try {/* www . j  a v a 2s .c om*/
            Object value = emptyInstances.get(returnType);
            if (value == null) {
                value = returnType.newInstance();
                emptyInstances.put(returnType, value);
            }
            Class<?> cls = value.getClass();
            while (cls != null && cls != Object.class) {
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    Object property = getEmptyObject(field.getType(), emptyInstances, level + 1);
                    if (property != null) {
                        try {
                            if (!field.isAccessible()) {
                                field.setAccessible(true);
                            }
                            field.set(value, property);
                        } catch (Throwable e) {
                        }
                    }
                }
                cls = cls.getSuperclass();
            }
            return value;
        } catch (Throwable e) {
            return null;
        }
    } else {
        return null;
    }
}

From source file:com.threewks.thundr.injection.InjectionContextImpl.java

private <T> T setFields(Class<T> type, T instance) {
    List<Field> fields = classIntrospector.listInjectionFields(type);
    for (Field field : fields) {
        try {//from w  w w .  j av  a 2 s. c  o  m
            Object beanProperty = get(field.getType(), field.getName());
            boolean accessible = field.isAccessible();
            field.setAccessible(true);
            field.set(instance, beanProperty);
            field.setAccessible(accessible);
        } catch (Exception e) {
            throw new InjectionException(e, "Failed to inject into %s.%s: %s", type.getName(), field.getName(),
                    getRootMessage(e));
        }
    }

    return instance;
}

From source file:org.mayocat.application.AbstractService.java

private void registerSettingsAsComponents(C settings) {
    List<Field> settingsFields = getAllFields(settings.getClass());
    for (Field field : settingsFields) {
        boolean isAccessible = field.isAccessible();
        try {// ww w.java 2  s .  c om
            try {
                field.setAccessible(true);
                Object value = field.get(settings);

                // Inject "as is" for components that only need an individual settings
                DefaultComponentDescriptor cd = new DefaultComponentDescriptor();
                cd.setRoleType(value.getClass());
                componentManager.registerComponent(cd, value);

                if (ExposedSettings.class.isAssignableFrom(value.getClass())) {

                    // Inject as settings
                    ExposedSettings exposedSettings = (ExposedSettings) value;
                    DefaultComponentDescriptor cd2 = new DefaultComponentDescriptor();
                    cd2.setRoleType(ExposedSettings.class);
                    cd2.setRoleHint(exposedSettings.getKey());
                    componentManager.registerComponent(cd2, value);
                }
            } finally {
                field.setAccessible(isAccessible);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    DefaultComponentDescriptor<C> cd = new DefaultComponentDescriptor<C>();
    cd.setRoleType(settings.getClass());
    componentManager.registerComponent(cd, settings);
}

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

/**
 * Define a property (accessible or not accessible)
 *
 * @param obj   instance to set the property on
 * @param field field to set the property on
 * @param value value to set//from   w  w  w . j  a va 2 s . c  o m
 * @throws IllegalAccessException
 */
private void setProperty(final Object obj, final Field field, final Object value)
        throws IllegalAccessException {
    boolean access = field.isAccessible();
    field.setAccessible(true);
    field.set(obj, value);
    field.setAccessible(access);
}

From source file:org.springframework.data.keyvalue.riak.RiakTemplate.java

private List<RiakLink> getLinksFromObject(final Object val) {
    final List<RiakLink> listOfLinks = new ArrayList<RiakLink>();
    ReflectionUtils.doWithFields(val.getClass(), new FieldCallback() {

        @Override/*from   w w w . ja  v  a 2  s.  c om*/
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (!field.isAccessible())
                ReflectionUtils.makeAccessible(field);

            org.springframework.data.keyvalue.riak.RiakLink linkAnnot = field
                    .getAnnotation(org.springframework.data.keyvalue.riak.RiakLink.class);
            String property = linkAnnot.property();
            Object referencedObj = field.get(val);
            Field prop = ReflectionUtils.findField(referencedObj.getClass(), property);

            if (!prop.isAccessible())
                ReflectionUtils.makeAccessible(prop);

            listOfLinks.add(new RiakLink(field.getType().getName(), prop.get(referencedObj).toString(),
                    linkAnnot.value()));

        }
    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {
            return field.isAnnotationPresent(org.springframework.data.keyvalue.riak.RiakLink.class);
        }
    });

    return listOfLinks;
}

From source file:activiti.common.persistence.util.ReflectHelper.java

/**
 * objfieldName/*w w  w  .  j  a va 2 s  .  c om*/
 * 
 * @param obj
 * @param fieldName
 * @param value
 * @throws SecurityException
 * @throws NoSuchFieldException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static boolean setValueByFieldName(Object obj, String fieldName, Object value) {
    try {
        // java.lang.Class.getDeclaredField() -
        // Field??Class?
        // Field
        Field field = obj.getClass().getDeclaredField(fieldName);
        /**
         * public void setAccessible(boolean flag) throws
         * SecurityException accessible  true
         * ??? Java  false ?? Java 
         * ? ReflectPermission("suppressAccessChecks") ??
         * checkPermission   flag  true??
         * Class  Constructor ? SecurityException 
         * java.lang.Class  Constructor  flag  true?
         * SecurityException ? flag - accessible  
         * SecurityException - ?
         */
        if (field.isAccessible()) {// ? accessible 
            field.set(obj, value);// ?? Field 
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
        return true;
    } catch (Exception e) {
    }
    return false;
}

From source file:com.sunsprinter.diffunit.core.injection.Injector.java

protected void inject(final Class<?> currentClass, final Class<?> testClass, final Object test)
        throws DiffUnitInjectionException {
    if (currentClass != Object.class) {
        for (final Field field : currentClass.getDeclaredFields()) {
            final DiffUnitInject annotation = field.getAnnotation(DiffUnitInject.class);
            if (annotation != null) {
                final Object key = StringUtils.isEmpty(annotation.objectId()) ? field.getType()
                        : annotation.objectId();

                final boolean fieldAccessible = field.isAccessible();
                try {
                    field.setAccessible(true);
                    field.set(test, getInjectionMap().get(key));
                } catch (final Exception e) {
                    throw new DiffUnitInjectionException(String.format(
                            "DiffUnit unable to inject field '%s' of class '%s' on test of class '%s'.  "
                                    + "Component key is '%s'.  Target field type is '%s'.",
                            field.getName(), currentClass.getName(), testClass.getName(), key,
                            field.getType().getName()), e);
                } finally {
                    field.setAccessible(fieldAccessible);
                }//  w  ww.  j  a  v  a2s  .c o  m
            }
        }

        inject(currentClass.getSuperclass(), testClass, test);
    }
}