Example usage for java.lang.reflect Field getDeclaringClass

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

Introduction

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

Prototype

@Override
public Class<?> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class or interface that declares the field represented by this Field object.

Usage

From source file:com.github.helenusdriver.driver.StatementBuilder.java

/**
 * Gets all the column names defined for a given field based on the specified
 * POJO class. The field must be annotated with {@link Column} and be part of
 * a class hierarchy annotated as an entity.
 *
 * @author paouelle//from ww w.j a v a2s  . com
 *
 * @param <T> The type of POJO associated with the request.
 *
 * @param  clazz the POJO class to get all the column names for
 * @param  field the field to get all the column names for
 * @return a non-<code>null</code> set of all the column names the specified
 *         field is annotated with
 * @throws NullPointerException if <code>clazz</code> or <code>name</code>
 *         is <code>null</code>
 * @throws IllegalArgumentException if the field or its class are not properly
 *         annotated or the field is not in a class that is the same or a base
 *         class of the specified class
 */
public static <T> Set<String> getColumnNamesFor(Class<T> clazz, Field field) {
    org.apache.commons.lang3.Validate.notNull(clazz, "invalid null class");
    org.apache.commons.lang3.Validate.notNull(field, "invalid null field name");
    org.apache.commons.lang3.Validate.isTrue(field.getDeclaringClass().isAssignableFrom(clazz),
            "field '%s.%s' is not defined in the class hieriarchy of: %s", field.getDeclaringClass().getName(),
            field.getName(), clazz.getClass().getName());
    return StatementManager.getManager().getColumnNamesFor(clazz, field);
}

From source file:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Field f, Class<?> ownerClass) {

    // TODO we could enable some methods from Object, like getClass
    if (f.getDeclaringClass().equals(java.lang.Object.class))
        return false;// handled here to avoid printing reasons

    if (f.getDeclaringClass().equals(java.lang.Thread.class))
        return false;// handled here to avoid printing reasons

    if (!Properties.USE_DEPRECATED && f.isAnnotationPresent(Deprecated.class)) {
        logger.debug("Skipping deprecated field {}", f.getName());
        return false;
    }//from  w ww  . j  a  v  a2  s.co  m

    if (f.isSynthetic()) {
        logger.debug("Skipping synthetic field {}", f.getName());
        return false;
    }

    if (f.getName().startsWith("ajc$")) {
        logger.debug("Skipping AspectJ field {}", f.getName());
        return false;
    }

    if (!f.getType().equals(String.class) && !canUse(f.getType())) {
        return false;
    }

    if (Modifier.isPublic(f.getModifiers())) {
        // It may still be the case that the field is defined in a non-visible superclass of the class
        // we already know we can use. In that case, the compiler would be fine with accessing the 
        // field, but reflection would start complaining about IllegalAccess!
        // Therefore, we set the field accessible to be on the safe side
        makeAccessible(f);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(f.getModifiers())) {
        //              && !Modifier.isProtected(f.getModifiers())) {
        String packageName = ClassUtils.getPackageName(ownerClass);

        String declaredPackageName = ClassUtils.getPackageName(f.getDeclaringClass());

        if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) {
            makeAccessible(f);
            return true;
        }
    }

    return false;
}

From source file:roboguice.inject.ViewListener.java

private <I> void prepareViewMembersInjector(TypeEncounter<I> typeEncounter, Field field) {
    if (field.isAnnotationPresent(InjectView.class)) {
        if (Modifier.isStatic(field.getModifiers()))
            throw new UnsupportedOperationException("Views may not be statically injected");
        else if (!View.class.isAssignableFrom(field.getType()))
            throw new UnsupportedOperationException("You may only use @InjectView on fields that extend View");
        else if (Context.class.isAssignableFrom(field.getDeclaringClass())
                && !Activity.class.isAssignableFrom(field.getDeclaringClass()))
            throw new UnsupportedOperationException("You may only use @InjectView in Activity contexts");
        else {//from   w  w  w .ja  va2s.c  om
            final f<?, ?> utils = FragmentUtil.hasSupport && (FragmentUtil.supportActivity
                    .isAssignableFrom(field.getDeclaringClass())
                    || FragmentUtil.supportFrag.fragmentType().isAssignableFrom(field.getDeclaringClass()))
                            ? FragmentUtil.supportFrag
                            : FragmentUtil.nativeFrag;

            typeEncounter.register(new ViewMembersInjector<I>(field, field.getAnnotation(InjectView.class),
                    typeEncounter, utils));
        }
    } else if (field.isAnnotationPresent(InjectFragment.class)) {
        if (!FragmentUtil.hasNative && !FragmentUtil.hasSupport) {
            throw new RuntimeException(new ClassNotFoundException("No fragment classes were available"));
        } else if (Modifier.isStatic(field.getModifiers())) {
            throw new UnsupportedOperationException("Fragments may not be statically injected");

        } else {
            final boolean assignableFromNative = FragmentUtil.hasNative
                    && FragmentUtil.nativeFrag.fragmentType().isAssignableFrom(field.getType());
            final boolean assignableFromSupport = FragmentUtil.hasSupport
                    && FragmentUtil.supportFrag.fragmentType().isAssignableFrom(field.getType());
            final boolean isSupportActivity = FragmentUtil.hasSupport
                    && FragmentUtil.supportActivity.isAssignableFrom(field.getDeclaringClass());
            final boolean isNativeActivity = !isSupportActivity
                    && Activity.class.isAssignableFrom(field.getDeclaringClass());

            if (isNativeActivity && assignableFromNative || isSupportActivity && assignableFromSupport) {
                typeEncounter.register(new ViewMembersInjector<I>(field,
                        field.getAnnotation(InjectFragment.class), typeEncounter,
                        isNativeActivity ? FragmentUtil.nativeFrag : FragmentUtil.supportFrag));
            } else if (isNativeActivity && !assignableFromNative) {
                // Error messages - these filters are comprehensive. The
                // final else block will never execute.
                throw new UnsupportedOperationException(
                        "You may only use @InjectFragment in native activities if fields are descended from type android.app.Fragment");
            } else if (!isSupportActivity && !isNativeActivity) {
                throw new UnsupportedOperationException(
                        "You may only use @InjectFragment in Activity contexts");
            } else if (isSupportActivity && !assignableFromSupport) {
                throw new UnsupportedOperationException(
                        "You may only use @InjectFragment in support activities if fields are descended from type android.support.v4.app.Fragment");
            } else {
                throw new RuntimeException("This should never happen.");
            }
        }
    }
}

From source file:info.archinnov.achilles.helper.EntityIntrospector.java

public Method findGetter(Class<?> beanClass, Field field) {
    log.debug("Find getter for field {} in class {}", field.getName(), beanClass.getCanonicalName());

    Method getterMethod = null;// w ww .  j  a v  a  2s.  co m
    String fieldName = field.getName();
    String[] getters = this.deriveGetterName(field);

    for (String getter : getters) {
        try {
            getterMethod = beanClass.getMethod(getter);
            if (getterMethod.getReturnType() != field.getType()) {
                throw new AchillesBeanMappingException("The getter for field '" + fieldName + "' of type '"
                        + field.getDeclaringClass().getCanonicalName() + "' does not return correct type");
            }
        } catch (NoSuchMethodException e) {
            // Do nothing here
        }
    }
    if (getterMethod == null) {
        throw new AchillesBeanMappingException("The getter for field '" + fieldName + "' of type '"
                + field.getDeclaringClass().getCanonicalName() + "' does not exist");
    }

    log.trace("Derived getter method : {}", getterMethod.getName());
    return getterMethod;
}

From source file:org.kaleidofoundry.spring.context.BeanContextPostProcessor.java

@Override
public Object postProcessBeforeInitialization(final Object beanInstance, final String beanName)
        throws BeansException {

    Set<Field> fields = ReflectionHelper.getAllDeclaredFields(beanInstance.getClass());

    for (Field field : fields) {
        // @Autowired is injected using spring bean
        if (field.isAnnotationPresent(Context.class) && !field.isAnnotationPresent(Autowired.class)
                && !field.isAnnotationPresent(Inject.class)) {

            final Context context = field.getAnnotation(Context.class);
            // do field is a runtime context class
            if (field.getType().isAssignableFrom(RuntimeContext.class)) {
                ReflectionUtils.makeAccessible(field);
                ReflectionUtils.setField(field, beanInstance,
                        RuntimeContext.createFrom(context, field.getName(), field.getDeclaringClass()));
            }/* ww w .j  a v  a  2 s.com*/
            // does the plugin interface have a provider specify
            else if (field.getType().isAnnotationPresent(Provider.class)) {

                try {
                    ReflectionUtils.makeAccessible(field);
                    Object fieldValue = field.get(beanInstance);

                    if (fieldValue == null) {
                        // create provider using annotation meta-information
                        final Provider provideInfo = field.getType().getAnnotation(Provider.class);
                        final Constructor<? extends ProviderService<?>> providerConstructor = provideInfo
                                .value().getConstructor(Class.class);
                        final ProviderService<?> fieldProviderInstance = providerConstructor
                                .newInstance(field.getType());

                        // invoke provides method with Context annotation meta-informations
                        final Method providesMethod = ReflectionUtils.findMethod(provideInfo.value(),
                                ProviderService.PROVIDES_METHOD, Context.class, String.class, Class.class);
                        // get the provider result
                        fieldValue = ReflectionUtils.invokeMethod(providesMethod, fieldProviderInstance,
                                context, field.getName(), field.getType());
                        // set the field that was not yet injected
                        ReflectionUtils.setField(field, beanInstance, fieldValue);
                    }

                } catch (IllegalArgumentException e) {
                    throw new BeanCreationException("Unexpected error during injection", e);
                } catch (IllegalAccessException e) {
                    throw new BeanCreationException("Unexpected error during injection", e);
                } catch (SecurityException e) {
                    throw new BeanCreationException("Unexpected error during injection", e);
                } catch (NoSuchMethodException e) {
                    throw new BeanCreationException("Unexpected error during injection", e);
                } catch (InstantiationException e) {
                    throw new BeanCreationException("Unexpected error during injection", e);
                } catch (InvocationTargetException ite) {
                    throw new BeanCreationException("", ite.getCause() != null ? ite.getCause()
                            : (ite.getTargetException() != null ? ite.getTargetException() : ite));
                } finally {

                }
            }
        }
    }

    return beanInstance;
}

From source file:richtercloud.reflection.form.builder.jpa.fieldhandler.JPAMappingFieldHandler.java

@Override
protected Pair<JComponent, ComponentHandler<?>> handle0(Field field, Object instance,
        final FieldUpdateListener updateListener, JPAReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException,
        InvocationTargetException, NoSuchMethodException, InstantiationException {
    if (field == null) {
        throw new IllegalArgumentException("fieldClass mustn't be null");
    }/*  w  w w.j a  va 2  s .  c o  m*/
    Type fieldType = field.getGenericType();
    Object fieldValue = field.get(instance);
    String fieldName = field.getName();
    Class<?> fieldDeclaringClass = field.getDeclaringClass();
    if (field.getAnnotation(Id.class) != null) {
        if (!(fieldType instanceof Class)) {
            throw new IllegalArgumentException("@Id annotated field has to be a class");
        }
        Class<?> fieldTypeClass = (Class<?>) fieldType;
        if (fieldTypeClass.equals(Long.class)) {
            Long fieldValueCast = (Long) field.get(instance);
            NumberPanel<Long> retValue;
            if (fieldType.equals(Long.class)) {
                retValue = new LongIdPanel(this.idGenerator, instance, fieldValueCast, //initialValue
                        messageHandler, fieldRetriever);
            } else {
                throw new IllegalArgumentException(
                        String.format("field type %s is not supported", fieldValue.getClass()));
            }
            retValue.addUpdateListener(new NumberPanelUpdateListener<Long>() {

                @Override
                public void onUpdate(NumberPanelUpdateEvent<Long> event) {
                    updateListener.onUpdate(new FieldUpdateEvent<>(event.getNewValue()));
                }
            });
            return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue,
                    LONG_ID_PANEL_COMPONENT_RESETTER);
        } else {
            throw new IllegalArgumentException(
                    String.format("@Id annotated field type %s not supported", field.getGenericType()));
        }
    }
    if (field.getAnnotation(ElementCollection.class) != null) {
        //can't be handled differently because otherwise a QueryPanel would
        //be tried to be used and IllegalArgumentException thrown at
        //initialization
        if (fieldValue != null && !(fieldValue instanceof List)) {
            throw new IllegalArgumentException("field values isn't an instance of List");
        }
        Pair<JComponent, ComponentHandler<?>> retValue = this.elementCollectionTypeHandler.handle(
                field.getGenericType(), (List<Object>) fieldValue, fieldName, fieldDeclaringClass,
                updateListener, reflectionFormBuilder);
        return retValue;
    }
    if (field.getAnnotation(OneToMany.class) != null || field.getAnnotation(ManyToMany.class) != null) {
        Pair<JComponent, ComponentHandler<?>> retValue = this.toManyTypeHandler.handle(field.getGenericType(),
                (List<Object>) fieldValue, fieldName, fieldDeclaringClass, updateListener,
                reflectionFormBuilder);
        return retValue;
    }
    if (field.getAnnotation(OneToOne.class) != null || field.getAnnotation(ManyToOne.class) != null) {
        Pair<JComponent, ComponentHandler<?>> retValue = this.toOneTypeHandler.handle(field.getGenericType(),
                fieldValue, fieldName, fieldDeclaringClass, updateListener, reflectionFormBuilder);
        return retValue;
    }
    if (field.getType() instanceof Class) {
        Class<?> fieldTypeClass = field.getType();
        if (fieldTypeClass.getAnnotation(Embeddable.class) != null) {
            FieldHandler fieldHandler = embeddableMapping.get(fieldType);
            JComponent retValue = fieldHandler.handle(field, instance, updateListener, reflectionFormBuilder);
            return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, fieldHandler);
        }
    }
    return super.handle0(field, instance, updateListener, reflectionFormBuilder);
}

From source file:jef.tools.reflect.ClassEx.java

/**
 * ??/*from w  w w  . ja v  a 2s.c o m*/
 * 
 * @param name
 * @return
 */
public Type getFieldGenericType(Field field) {
    Assert.notNull(field);
    ClassEx cw = this;
    if (field.getDeclaringClass() != this.cls) {
        Type type = GenericUtils.getSuperType(null, cls, field.getDeclaringClass());
        cw = new ClassEx(type);
    }
    return BeanUtils.getBoundType(field.getGenericType(), cw);
}

From source file:org.jgentleframework.reflection.metadata.DefinitionImpl.java

@Override
public Class<?> getOwnerClass() {

    if (isInterpretedOfClass()) {
        return (Class<?>) this.getKey();
    } else if (isInterpretedOfConstructor()) {
        Constructor<?> constructor = (Constructor<?>) this.getKey();
        return constructor.getDeclaringClass();
    } else if (isInterpretedOfField()) {
        Field field = (Field) this.getKey();
        return field.getDeclaringClass();
    } else if (isInterpretedOfMethod()) {
        Method method = (Method) this.getKey();
        return method.getDeclaringClass();
    } else {//from  w w  w .  ja v  a2  s . c  o m
        if (log.isWarnEnabled()) {
            log.warn("This definition is not interpreted from anything");
        }
        return null;
    }
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

private byte[] columnFamilyNameFromHBaseFieldAnnotatedField(final Field hbaseFieldAnnotatedField) {
    return hbaseFieldAnnotatedField.getAnnotation(HBaseField.class).columnFamilyName().isEmpty()
            ? defaultColumnFamilyNameFrom(hbaseFieldAnnotatedField.getDeclaringClass())
            : Bytes.toBytes(hbaseFieldAnnotatedField.getAnnotation(HBaseField.class).columnFamilyName());
}

From source file:com.mylife.hbase.mapper.HBaseEntityMapper.java

private byte[] columnFamilyNameFromHBaseMapFieldAnnotatedField(final Field hbaseMapFieldAnnotatedField) {
    return hbaseMapFieldAnnotatedField.getAnnotation(HBaseMapField.class).columnFamilyName().isEmpty()
            ? defaultColumnFamilyNameFrom(hbaseMapFieldAnnotatedField.getDeclaringClass())
            : Bytes.toBytes(hbaseMapFieldAnnotatedField.getAnnotation(HBaseMapField.class).columnFamilyName());
}