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.cnksi.core.tools.utils.Reflections.java

/**
 * ?private/protected???public?????JDKSecurityManager
 */// w  w w.j  a  va  2  s  .com
public static void makeAccessible(Field field) {

    if ((!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
            || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}

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

public static void makeAccessible(Field field) {
    if (!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
        field.setAccessible(true);//from  w  ww. ja  va  2  s .com
    }
}

From source file:org.unitils.mock.core.proxy.CloneUtil.java

/**
 * Clones all values in all fields of the given class and superclasses.
 *
 * @param clazz           The current class
 * @param instanceToClone The instance, not null
 * @param clonedInstance  The clone, not null
 * @param cloneCache      The cached clones, not null
 *///from  ww w .  j  ava  2s.  c om
protected static void cloneFields(Class<?> clazz, Object instanceToClone, Object clonedInstance,
        Map<Object, Object> cloneCache) throws Throwable {
    if (clazz == null || Object.class.equals(clazz)) {
        return;
    }

    Field[] fields = clazz.getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);

    for (Field field : fields) {
        // skip static fields
        if (isStatic(field.getModifiers())) {
            continue;
        }
        if (field.getDeclaringClass().getName().startsWith("org.hibernate")
                && isTransient(field.getModifiers())) {
            continue;
        }

        Object fieldValue = field.get(instanceToClone);
        Object clonedFieldValue = cloneObject(fieldValue, cloneCache);
        field.set(clonedInstance, clonedFieldValue);
    }
    cloneFields(clazz.getSuperclass(), instanceToClone, clonedInstance, cloneCache);
}

From source file:org.gradle.api.internal.tasks.options.FieldOptionElement.java

public static FieldOptionElement create(Option option, Field field,
        OptionNotationParserFactory optionNotationParserFactory) {
    String optionName = calOptionName(option, field);
    Class<?> optionType = calculateOptionType(field.getType());
    ValueAwareNotationParser<?> notationParser = createNotationParserOrFail(optionNotationParserFactory,
            optionName, optionType, field.getDeclaringClass());
    return new FieldOptionElement(field, optionName, option, optionType, notationParser);
}

From source file:org.eclipse.wb.internal.core.utils.external.ExternalFactoriesHelper.java

/**
 * @return the result of {@link IConfigurationElement#createExecutableExtension(String)}.
 *//*w ww. j  av a2  s.  com*/
@SuppressWarnings("unchecked")
public static synchronized <T> T createExecutableExtension(final IConfigurationElement element,
        final String classAttributeName) {
    return ExecutionUtils.runObject(new RunnableObjectEx<T>() {
        public T runObject() throws Exception {
            Bundle extensionBundle = getExtensionBundle(element);
            String className = getRequiredAttribute(element, classAttributeName);
            Class<?> clazz = extensionBundle.loadClass(className);
            // try to find singleton INSTANCE
            {
                Field instanceField = ReflectionUtils.getFieldByName(clazz, "INSTANCE");
                if (instanceField != null && instanceField.getDeclaringClass() == clazz) {
                    return (T) instanceField.get(null);
                }
            }
            // well, create new instance
            return (T) element.createExecutableExtension(classAttributeName);
        }
    });
}

From source file:info.archinnov.achilles.internal.metadata.parsing.PropertyParser.java

public static String getIndexName(Field field) {
    log.debug("Check @Index annotation on field {} of class {}", field.getName(),
            field.getDeclaringClass().getCanonicalName());
    String indexName = null;//  w ww . j  a v a2  s .co m
    Index index = field.getAnnotation(Index.class);
    if (index != null) {
        indexName = index.name();
    }
    return indexName;
}

From source file:org.apache.axis.utils.BeanUtils.java

public static BeanPropertyDescriptor[] processPropertyDescriptors(PropertyDescriptor[] rawPd, Class cls,
        TypeDesc typeDesc) {/*from   w ww  . j a v a2 s.c  o  m*/

    // Create a copy of the rawPd called myPd
    BeanPropertyDescriptor[] myPd = new BeanPropertyDescriptor[rawPd.length];

    ArrayList pd = new ArrayList();

    try {
        for (int i = 0; i < rawPd.length; i++) {
            // Skip the special "any" field
            if (rawPd[i].getName().equals(Constants.ANYCONTENT))
                continue;
            pd.add(new BeanPropertyDescriptor(rawPd[i]));
        }

        // Now look for public fields
        Field fields[] = cls.getFields();
        if (fields != null && fields.length > 0) {
            // See if the field is in the list of properties
            // add it if not.
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                // skip if field come from a java.* or javax.* package
                // WARNING: Is this going to make bad things happen for
                // users JavaBeans?  Do they WANT these fields serialzed?
                String clsName = f.getDeclaringClass().getName();
                if (clsName.startsWith("java.") || clsName.startsWith("javax.")) {
                    continue;
                }
                // skip field if it is final, transient, or static
                if (!(Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())
                        || Modifier.isTransient(f.getModifiers()))) {
                    String fName = f.getName();
                    boolean found = false;
                    for (int j = 0; j < rawPd.length && !found; j++) {
                        String pName = ((BeanPropertyDescriptor) pd.get(j)).getName();
                        if (pName.length() == fName.length()
                                && pName.substring(0, 1).equalsIgnoreCase(fName.substring(0, 1))) {

                            found = pName.length() == 1 || pName.substring(1).equals(fName.substring(1));
                        }
                    }

                    if (!found) {
                        pd.add(new FieldPropertyDescriptor(f.getName(), f));
                    }
                }
            }
        }

        // If typeDesc meta data exists, re-order according to the fields
        if (typeDesc != null && typeDesc.getFields(true) != null) {
            ArrayList ordered = new ArrayList();
            // Add the TypeDesc elements first
            FieldDesc[] fds = typeDesc.getFields(true);
            for (int i = 0; i < fds.length; i++) {
                FieldDesc field = fds[i];
                if (field.isElement()) {
                    boolean found = false;
                    for (int j = 0; j < pd.size() && !found; j++) {
                        if (field.getFieldName().equals(((BeanPropertyDescriptor) pd.get(j)).getName())) {
                            ordered.add(pd.remove(j));
                            found = true;
                        }
                    }
                }
            }
            // Add the remaining elements
            while (pd.size() > 0) {
                ordered.add(pd.remove(0));
            }
            // Use the ordered list
            pd = ordered;
        }

        myPd = new BeanPropertyDescriptor[pd.size()];
        for (int i = 0; i < pd.size(); i++) {
            myPd[i] = (BeanPropertyDescriptor) pd.get(i);
        }
    } catch (Exception e) {
        log.error(Messages.getMessage("badPropertyDesc00", cls.getName()), e);
        throw new InternalException(e);
    }

    return myPd;
}

From source file:org.evosuite.setup.TestUsageChecker.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)) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

        if (Properties.hasTargetClassBeenLoaded() && !f.getDeclaringClass().equals(targetClass)) {
            logger.debug("Skipping deprecated field " + f.getName());
            return false;
        }//from w  w w.j a  va2 s.c  om
    }

    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;
    }

    // in, out, err
    if (f.getDeclaringClass().equals(FileDescriptor.class)) {
        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
        TestClusterUtils.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)) {
            TestClusterUtils.makeAccessible(f);
            return true;
        }
    }

    return false;
}

From source file:org.evosuite.instrumentation.mutation.ReplaceVariable.java

/**
 * This replicates TestUsageChecker.canUse but we need to avoid that
 * we try to access Properties.getTargetClassAndDontInitialise
 *
 * @param f/* w  w  w  .  j  a  va 2  s. c o m*/
 * @return
 */
public static boolean canUse(Field f) {

    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 (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;
    }

    // in, out, err
    if (f.getDeclaringClass().equals(FileDescriptor.class)) {
        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
        TestClusterUtils.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())) {
        String packageName = ClassUtils.getPackageName(f.getDeclaringClass());

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

    return false;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Field f) {
    if (f.isAnnotationPresent(I18n.class)) {
        if (f.getAnnotation(I18n.class).value().length() > 0) {
            return f.getAnnotation(I18n.class).value();
        } else {/*w w w.ja  v a2  s . c  o  m*/
            return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
        }
    }
    // else if(f.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = f.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return f.getDeclaringClass().getName() + CODE_SEPARATOR + f.getName();
}