Java Code Examples for java.lang.reflect.Field#getDeclaringClass()

The following examples show how to use java.lang.reflect.Field#getDeclaringClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReadCSVStep.java    From pipeline-utility-steps-plugin with MIT License 6 votes vote down vote up
@Override
public boolean permitsStaticFieldGet(@Nonnull Field field) {
    final Class<?> aClass = field.getDeclaringClass();
    final Package aPackage = aClass.getPackage();

    if (aPackage == null) {
        return false;
    }

    if (!aPackage.getName().equals(ORG_APACHE_COMMONS_CSV)) {
        return false;
    }

    if (aClass == CSVFormat.class) {
        return true;
    }

    return false;
}
 
Example 2
Source File: PojoMethodFactory.java    From openpojo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Setter Method for a field.
 *
 * @param field
 *     The field to lookup the setter on.
 * @return The setter method or null if none exist.
 */
public static PojoMethod getFieldSetter(final Field field) {
  PojoMethod pojoMethod = null;

  for (final String candidateName : generateSetMethodNames(field)) {
    final Class<?> clazz = field.getDeclaringClass();
    pojoMethod = PojoMethodFactory.getMethod(clazz, candidateName, field.getType());

    if (pojoMethod != null) {
      if (pojoMethod.isAbstract()) {
        LoggerFactory.getLogger(
            PojoMethodFactory.class).warn("Setter=[{0}] in class=[{1}] rejected due to method being abstract",
            pojoMethod.getName(), field.getDeclaringClass().getName());
        pojoMethod = null;
      }
      break;
    }
  }
  return pojoMethod;
}
 
Example 3
Source File: Permissions.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether a field explicitly disallows JEXL introspection.
 * @param field the field to check
 * @return true if JEXL is allowed to introspect, false otherwise
 */
public boolean allow(Field field) {
    if (field == null) {
        return false;
    }
    if (!Modifier.isPublic(field.getModifiers())) {
        return false;
    }
    Class<?> clazz = field.getDeclaringClass();
    if (!allow(clazz, false)) {
        return false;
    }
    // is field annotated with nojexl ?
    NoJexl nojexl = field.getAnnotation(NoJexl.class);
    if (nojexl != null) {
        return false;
    }
    return true;
}
 
Example 4
Source File: CheckInjectionPointUsage.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void validate(final EjbModule ejbModule) {
    if (ejbModule.getBeans() == null) {
        return;
    }

    try {
        for (final Field field : ejbModule.getFinder().findAnnotatedFields(Inject.class)) {
            if (!field.getType().equals(InjectionPoint.class) || !HttpServlet.class.isAssignableFrom(field.getDeclaringClass())) {
                continue;
            }

            final Annotation[] annotations = field.getAnnotations();
            if (annotations.length == 1 || (annotations.length == 2 && field.getAnnotation(Default.class) != null)) {
                throw new DefinitionException("Can't inject InjectionPoint in " + field.getDeclaringClass());
            } // else we should check is there is no other qualifier than @Default but too early
        }
    } catch (final NoClassDefFoundError noClassDefFoundError) {
        // ignored: can't check but maybe it is because of an optional dep so ignore it
        // not important to skip it since the failure will be reported elsewhere
        // this validator doesn't check it
    }
}
 
Example 5
Source File: FieldFinder.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finds public field (static or non-static)
 * that is declared in public class.
 *
 * @param type  the class that can have field
 * @param name  the name of field to find
 * @return object that represents found field
 * @throws NoSuchFieldException if field is not found
 * @see Class#getField
 */
public static Field findField(Class<?> type, String name) throws NoSuchFieldException {
    if (name == null) {
        throw new IllegalArgumentException("Field name is not set");
    }
    Field field = type.getField(name);
    if (!Modifier.isPublic(field.getModifiers())) {
        throw new NoSuchFieldException("Field '" + name + "' is not public");
    }
    type = field.getDeclaringClass();
    if (!Modifier.isPublic(type.getModifiers()) || !isPackageAccessible(type)) {
        throw new NoSuchFieldException("Field '" + name + "' is not accessible");
    }
    return field;
}
 
Example 6
Source File: MetaData.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 7
Source File: MetaData.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 8
Source File: DependencyDescriptor.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new descriptor for a field.
 * @param field the field to wrap
 * @param required whether the dependency is required
 * @param eager whether this dependency is 'eager' in the sense of
 * eagerly resolving potential target beans for type matching
 */
public DependencyDescriptor(Field field, boolean required, boolean eager) {
	Assert.notNull(field, "Field must not be null");
	this.field = field;
	this.declaringClass = field.getDeclaringClass();
	this.fieldName = field.getName();
	this.required = required;
	this.eager = eager;
}
 
Example 9
Source File: MetaData.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 10
Source File: PropertyMapper.java    From anno4j with Apache License 2.0 5 votes vote down vote up
public String findPredicate(Field field) {
	Class<?> dc = field.getDeclaringClass();
	String key = dc.getName() + "#" + field.getName();
	if (properties.containsKey(key))
		return (String) properties.get(key);
	Iri rdf = field.getAnnotation(Iri.class);
	if (rdf == null)
		return null;
	return rdf.value();
}
 
Example 11
Source File: UnsafeFieldAccess.java    From jadira with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private UnsafeFieldAccess(Field f) {
	this.field = f;
	this.declaringClass = (Class<C>) f.getDeclaringClass();
	this.type = (Class<?>) f.getType();
	this.fieldOffset = UNSAFE_OPERATIONS.getObjectFieldOffset(f);
}
 
Example 12
Source File: GetterBuilder.java    From SimpleFlatMapper with MIT License 4 votes vote down vote up
public static byte[] createObjectGetter(final String className, final Field field) throws Exception {

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        MethodVisitor mv;

        Class<?> target = field.getDeclaringClass();
        Class<?> property = field.getType();

        String targetType = toType(target);
        String propertyType = toType(property);
        String classType = toType(className);

        cw.visit(
                V1_6,
                ACC_PUBLIC + ACC_FINAL + ACC_SUPER,
                classType,
                "Ljava/lang/Object;L" + GETTER_TYPE + "<L" + targetType + ";" + AsmUtils.toTargetTypeDeclaration(propertyType) + ">;",
                "java/lang/Object", new String[] {GETTER_TYPE});

        {
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
            mv.visitCode();
            mv.visitVarInsn(ALOAD, 0);
            mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
            mv.visitInsn(RETURN);
            mv.visitMaxs(1, 1);
            mv.visitEnd();
        }
        {
            mv = cw.visitMethod(ACC_PUBLIC, "get",
                    "(" + AsmUtils.toTargetTypeDeclaration(targetType) + ")" + AsmUtils.toTargetTypeDeclaration(propertyType), null,
                    new String[] { "java/lang/Exception" });
            mv.visitCode();
            mv.visitVarInsn(ALOAD, 1);

            mv.visitFieldInsn(GETFIELD, targetType, field.getName(), AsmUtils.toTargetTypeDeclaration(propertyType));

            mv.visitInsn(ARETURN);
            mv.visitMaxs(1, 2);
            mv.visitEnd();
        }

        appendBridge(cw, targetType, propertyType, classType);

        appendToString(cw);

        cw.visitEnd();

        return AsmUtils.writeClassToFile(className, cw.toByteArray());

    }
 
Example 13
Source File: Serializer.java    From jease with GNU General Public License v3.0 4 votes vote down vote up
public boolean isNodeDeclaringClass(Field field) {
	return field.getDeclaringClass() == Node.class;
}
 
Example 14
Source File: WeldJunit5Extension.java    From weld-junit with Apache License 2.0 4 votes vote down vote up
private void startWeldContainerIfAppropriate(TestInstance.Lifecycle expectedLifecycle, ExtensionContext context) throws Exception {
    // is the lifecycle is what we expect it to be, start Weld container
    if (determineTestLifecycle(context).equals(expectedLifecycle)) {
        Object testInstance = context.getTestInstance().orElseGet(null);
        if (testInstance == null) {
            throw new IllegalStateException("ExtensionContext.getTestInstance() returned empty Optional!");
        }

        // store info about explicit param injection, either from global settings or from annotation on the test class
        storeExplicitParamResolutionInformation(context);

        // all found fields which are WeldInitiator and have @WeldSetup annotation
        List<Field> foundInitiatorFields = new ArrayList<>();
        WeldInitiator initiator = null;
        // We will go through class hierarchy in search of @WeldSetup field (even private)
        for (Class<?> clazz = testInstance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
            // Find @WeldSetup field using getDeclaredFields() - this allows even for private fields
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(WeldSetup.class)) {
                    Object fieldInstance;
                    try {
                        fieldInstance = field.get(testInstance);
                    } catch (IllegalAccessException e) {
                        // In case we cannot get to the field, we need to set accessibility as well
                        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                            field.setAccessible(true);
                            return null;
                        });
                        fieldInstance = field.get(testInstance);
                    }
                    if (fieldInstance != null && fieldInstance instanceof WeldInitiator) {
                        initiator = (WeldInitiator) fieldInstance;
                        foundInitiatorFields.add(field);
                    } else {
                        // Field with other type than WeldInitiator was annotated with @WeldSetup
                        throw new IllegalStateException("@WeldSetup annotation should only be used on a field of type"
                                + " WeldInitiator but was found on a field of type " + field.getType() + " which is declared "
                                + "in class " + field.getDeclaringClass());
                    }
                }
            }
        }
        // Multiple occurrences of @WeldSetup in the hierarchy will lead to an exception
        if (foundInitiatorFields.size() > 1) {
            throw new IllegalStateException(foundInitiatorFields.stream().map(f -> "Field type - " + f.getType() + " which is "
                    + "in " + f.getDeclaringClass()).collect(Collectors.joining("\n", "Multiple @WeldSetup annotated fields found, "
                    + "only one is allowed! Fields found:\n", "")));
        }

        // at this point we can be sure that either no or exactly one WeldInitiator was found
        if (initiator == null) {
            Weld weld = WeldInitiator.createWeld();
            WeldInitiator.Builder builder = WeldInitiator.from(weld);

            weldInit(testInstance, context, weld, builder);

            // Apply discovered enrichers
            for (WeldJunitEnricher enricher : getEnrichersFromStore(context)) {
                String property = System.getProperty(enricher.getClass().getName());
                if (property == null || Boolean.parseBoolean(property)) {
                    enricher.enrich(testInstance, context, weld, builder);
                }
            }

            initiator = builder.build();
        }
        setInitiatorToStore(context, initiator);

        // this ensures the test class is injected into
        // in case of nested tests, this also injects into any outer classes
        Set<Object> enclosingClasses = getInstancesToInjectToFromRootStore(context);
        if (enclosingClasses != null) {
            initiator.addObjectsToInjectInto(enclosingClasses);
        }

        // and finally, init Weld
        setContainerToStore(context, initiator.initWeld(testInstance));
    }
}
 
Example 15
Source File: ReflectionNavigator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public Class getDeclaringClassForField(Field field) {
    return field.getDeclaringClass();
}
 
Example 16
Source File: AnnotationEdmProvider.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
private TypeBuilder withClass(final Class<?> aClass) {
  baseEntityType = createBaseEntityFqn(aClass);

  if (Modifier.isAbstract(aClass.getModifiers())) {
    isAbstract = true;
  }

  Field[] fields = aClass.getDeclaredFields();
  for (Field field : fields) {
    EdmProperty ep = field.getAnnotation(EdmProperty.class);
    if (ep != null) {
      Property property = createProperty(ep, field);
      properties.add(property);
      EdmKey eti = field.getAnnotation(EdmKey.class);
      if (eti != null) {
        keyProperties.add(createKeyProperty(ep, field));
      }
      EdmMediaResourceMimeType emrmt = field.getAnnotation(EdmMediaResourceMimeType.class);
      if (emrmt !=null) {
        mediaResourceMimeTypeKey = property.getName();
      }
      EdmMediaResourceSource emrs = field.getAnnotation(EdmMediaResourceSource.class);
      if (emrs !=null) {
        mediaResourceSourceKey =  property.getName();
      }
    }
    EdmNavigationProperty enp = field.getAnnotation(EdmNavigationProperty.class);
    if (enp != null) {
      Class<?> fromClass = field.getDeclaringClass();
      Class<?> toClass = ClassHelper.getFieldType(field);
      AnnotationHelper.AnnotatedNavInfo info = ANNOTATION_HELPER.getCommonNavigationInfo(fromClass, toClass);

      final NavigationProperty navProperty = createNavigationProperty(namespace, field, info);
      navProperties.add(navProperty);
      Association association = createAssociation(info);
      associations.add(association);
    }
    EdmMediaResourceContent emrc = field.getAnnotation(EdmMediaResourceContent.class);
    if (emrc != null) {
      isMediaResource = true;
    }
  }

  return this;
}
 
Example 17
Source File: SerializableTypeWrapper.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
public FieldTypeProvider(Field field) {
	this.fieldName = field.getName();
	this.declaringClass = field.getDeclaringClass();
	this.field = field;
}
 
Example 18
Source File: TableFieldInfo.java    From Roothub with GNU Affero General Public License v3.0 4 votes vote down vote up
public TableFieldInfo(Field field) {
	this.column = StringUtils.camelToUnderline(field.getName());
	this.property = field.getName();
	this.propertyType = field.getType();
	this.modelClass = field.getDeclaringClass();
}
 
Example 19
Source File: SerializableTypeWrapper.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public FieldTypeProvider(Field field) {
	this.fieldName = field.getName();
	this.declaringClass = field.getDeclaringClass();
	this.field = field;
}
 
Example 20
Source File: PojoFieldUtils.java    From flink with Apache License 2.0 2 votes vote down vote up
/**
 * Writes a field to the given {@link DataOutputView}.
 *
 * <p>This write method avoids Java serialization, by writing only the classname of the field's declaring class
 * and the field name. The written field can be read using {@link #readField(DataInputView, ClassLoader)}.
 *
 * @param out the output view to write to.
 * @param field the field to write.
 */
static void writeField(DataOutputView out, Field field) throws IOException {
	Class<?> declaringClass = field.getDeclaringClass();
	out.writeUTF(declaringClass.getName());
	out.writeUTF(field.getName());
}