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

The following are Jave code examples for showing how to use getDeclaringClass() of the java.lang.reflect.Field class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: openNaEF   File: JournalWriter.java   View Source Code Vote up 6 votes
final void printNewField(Field field) {
    if (!mvoMeta_.isNewField(field)) {
        throw new IllegalArgumentException();
    }

    mvoMeta_.registerField(field, null);

    Class<? extends MVO> declaringClass = (Class<? extends MVO>) field.getDeclaringClass();
    if (mvoMeta_.isNewClass(declaringClass)) {
        printNewClass(declaringClass);
    }

    int classId = mvoMeta_.getClassId(declaringClass);
    int fieldId = mvoMeta_.getFieldId(field);
    loggingStream_.println
            (concat
                    (EntryType.FIELD_ID.id, hexInt(fieldId), hexInt(classId), field.getName()));
}
 
Example 2
Project: meparty   File: FieldUtil.java   View Source Code Vote up 6 votes
/**
 * Returns set method of the field if any public set method found.
 *
 * @param field field
 * @return set method.
 */
public static Optional<Method> findSetMethod(final Field field) {

  AssertHelper.notNull(field);

  Class<?> declaringClass = field.getDeclaringClass();

  Method[] methods = declaringClass.getMethods();
  String capitalizedFieldName = StringHelper.capitalizeFirstLetter(field.getName());

  Optional<Method> optionalMethod = Arrays.stream(methods)
      .filter(m ->
          m.getName().equals("set" + capitalizedFieldName)
              && m.getParameterCount() == 1
              && Arrays.stream(m.getParameterTypes()).anyMatch(p -> p.equals(field.getType())
              || PrimitiveHelper.getOppositeClass(p).equals(field.getType())))
      .findFirst();

  return optionalMethod;
}
 
Example 3
Project: openjdk-jdk10   File: FieldFinder.java   View Source Code Vote up 6 votes
/**
 * 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");
    }
    if (!FinderUtils.isExported(type)) {
        throw new NoSuchFieldException("Field '" + name + "' is not accessible");
    }
    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 4
Project: solo-spring   File: Reflections.java   View Source Code Vote up 6 votes
public static Field getHideField(final Field superclassField, final Class<?> subclass) {
	final Class<?> superclass = superclassField.getDeclaringClass();
	Class<?> currentClass = subclass;

	if (!superclass.isAssignableFrom(subclass)) {
		throw new RuntimeException("Class[" + subclass + "] is not superclass" + " of class[" + subclass + "]");
	}

	while (!currentClass.equals(superclass)) {
		try {
			final Field m = currentClass.getDeclaredField(superclassField.getName());

			if (matchInheritance(m, superclassField)) {
				return m;
			}
		} catch (final Exception ex) {
		}

		currentClass = currentClass.getSuperclass();
	}

	return superclassField;
}
 
Example 5
Project: openjdk-jdk10   File: FacetIntrospector.java   View Source Code Vote up 6 votes
/**
 * Returns the fields for the class facet.
 * @return the fields for the class facet.
 */
Collection<Field> getFields() {
    if(isRestricted) {
        // NOTE: we can't do anything here. Unlike with methods in AccessibleMethodsLookup, we can't just return
        // the fields from a public superclass, because this class might define same-named fields which will shadow
        // the superclass fields, and we have no way to know if they do, since we're denied invocation of
        // getFields(). Therefore, the only correct course of action is to not expose any public fields from a class
        // defined in a restricted package.
        return Collections.emptySet();
    }

    final Field[] fields = clazz.getFields();
    final Collection<Field> cfields = new ArrayList<>(fields.length);
    for(final Field field: fields) {
        final boolean isStatic = Modifier.isStatic(field.getModifiers());
        if(isStatic && clazz != field.getDeclaringClass()) {
            // ignore inherited static fields
            continue;
        }

        if(instance != isStatic && isAccessible(field)) {
            cfields.add(field);
        }
    }
    return cfields;
}
 
Example 6
Project: Equella   File: AnnotatedPlugResourceScanner.java   View Source Code Vote up 6 votes
@SuppressWarnings("nls")
public void setupLabels(Section section)
{
	for( Field field : componentLabels.keySet() )
	{
		try
		{
			AbstractRenderedComponent<?> comp = (AbstractRenderedComponent<?>) field.get(section);
			comp.setLabel(componentLabels.get(field));
		}
		catch( Exception e )
		{
			throw new RuntimeException(field.getName() + " on " + field.getDeclaringClass()
				+ " has @PlugKey but probably missing @Component?", e);
		}
	}
}
 
Example 7
Project: java-php-serializer   File: ObjectAdapter.java   View Source Code Vote up 6 votes
/**
 * Writes fields using the specified writer.
 *
 * @param object The object that owns the field.
 * @param fields The fields to be written.
 * @param writer The writer to use for writing the fields.
 * @param context The serialization context.
 */
protected void writeFields(
    T object,
    Field[] fields,
    Writer writer,
    Context context
)
{
    NamingStrategy namingStrategy = context.getNamingStrategy();

    for (Field field : fields) {
        String name = namingStrategy.getFieldName(field);
        Class<?> declaringClass = field.getDeclaringClass();
        String fieldClass = namingStrategy.getClassName(declaringClass);

        writer.writeProperty(name, fieldClass, getModifiers(field));
        context.write(ReflectionUtils.getValue(object, field), writer);
    }
}
 
Example 8
Project: OperatieBRP   File: BmrFieldMetaInfo.java   View Source Code Vote up 5 votes
/**
 * Maakt een nieuw BmrFieldMetaInfo object voor het gegeven veld.
 *
 * @param field het veld waarvan de meta informatie moet worden gemaakt
 * @return BrmFieldMetaInfo
 */
public static BmrFieldMetaInfo getInstance(final Field field) {
    final Map<String, Class<?>> elementNaamTypeMap = new LinkedHashMap<>();
    final XmlChild xmlChildAnnotatie = field.getAnnotation(XmlChild.class);
    final String xmlChildNaam = xmlChildAnnotatie != null ? xmlChildAnnotatie.naam() : "";
    final int xmlChildVolgorde = xmlChildAnnotatie != null ? xmlChildAnnotatie.volgorde() : 0;
    initialiseerElementNaamTypeMapping(elementNaamTypeMap, field, xmlChildNaam);
    return new BmrFieldMetaInfo(field.getDeclaringClass(), field, findGetterMethode(field), elementNaamTypeMap, xmlChildVolgorde);
}
 
Example 9
Project: lams   File: DependencyDescriptor.java   View Source Code Vote up 5 votes
/**
 * 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 10
Project: openjdk-jdk10   File: MetaData.java   View Source Code Vote up 5 votes
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 11
Project: EasyML   File: BaseDao.java   View Source Code Vote up 5 votes
/**
 * Set the corresponding field based on the entered string value
 *
 * @param instance object
 * @param strVal   input value
 * @param field    input field
 * @throws IntrospectionException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
public static void invoke(Object instance, String strVal, Field field)
		throws IntrospectionException, InvocationTargetException, IllegalAccessException {

	if (strVal == null) strVal = "";

	Object val = parser.parse(strVal, field.getType());

	PropertyDescriptor pd = new PropertyDescriptor(field.getName(), field.getDeclaringClass());
	Method m = pd.getWriteMethod();// get write method
	m.invoke(instance, val);
}
 
Example 12
Project: OpenJSharp   File: MetaData.java   View Source Code Vote up 5 votes
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 13
Project: OpenJSharp   File: FieldFinder.java   View Source Code Vote up 5 votes
/**
 * 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 14
Project: jdk8u-jdk   File: MetaData.java   View Source Code Vote up 5 votes
protected Expression instantiate(Object oldInstance, Encoder out) {
    Field f = (Field)oldInstance;
    return new Expression(oldInstance,
            f.getDeclaringClass(),
            "getField",
            new Object[]{f.getName()});
}
 
Example 15
Project: sstable-adaptor   File: Ref.java   View Source Code Vote up 4 votes
Pair<Object, Field> nextChild() throws IllegalAccessException
{
    //If the last child returned was a key from a map, the value from that entry is stashed
    //so it can be returned next
    if (mapEntryValue != null)
    {
        Pair<Object, Field> retval = Pair.create(mapEntryValue, field);
        mapEntryValue = null;
        return retval;
    }

    //If o is a ConcurrentMap, BlockingQueue, or Object[], then an iterator will be stored to return the elements
    if (collectionIterator != null)
    {
        if (!collectionIterator.hasNext())
            return null;
        Object nextItem = null;
        //Find the next non-null element to traverse since returning null will cause the visitor to stop
        while (collectionIterator.hasNext() && (nextItem = collectionIterator.next()) == null){}
        if (nextItem != null)
        {
            if (isMapIterator & nextItem instanceof Map.Entry)
            {
                Map.Entry entry = (Map.Entry)nextItem;
                mapEntryValue = entry.getValue();
                return Pair.create(entry.getKey(), field);
            }
            return Pair.create(nextItem, field);
        }
        else
        {
            return null;
        }
    }

    //Basic traversal of an object by its member fields
    //Don't return null values as that indicates no more objects
    while (true)
    {
        Field nextField = nextField();
        if (nextField == null)
            return null;

        //A weak reference isn't strongly reachable
        //subclasses of WeakReference contain strong references in their fields, so those need to be traversed
        //The weak reference fields are in the common Reference class base so filter those out
        if (o instanceof WeakReference & nextField.getDeclaringClass() == Reference.class)
            continue;

        Object nextObject = nextField.get(o);
        if (nextObject != null)
            return Pair.create(nextField.get(o), nextField);
    }
}
 
Example 16
Project: boohee_v5.6   File: FieldInfo.java   View Source Code Vote up 4 votes
public FieldInfo(String name, Method method, Field field, Class<?> clazz, Type type, int ordinal, int serialzeFeatures) {
    Class<?> fieldClass;
    Type fieldType;
    Type genericFieldType;
    this.ordinal = 0;
    this.getOnly = false;
    this.name = name;
    this.method = method;
    this.field = field;
    this.ordinal = ordinal;
    this.serialzeFeatures = serialzeFeatures;
    if (method != null) {
        TypeUtils.setAccessible(method);
    }
    if (field != null) {
        TypeUtils.setAccessible(field);
    }
    if (method != null) {
        if (method.getParameterTypes().length == 1) {
            fieldClass = method.getParameterTypes()[0];
            fieldType = method.getGenericParameterTypes()[0];
        } else {
            fieldClass = method.getReturnType();
            fieldType = method.getGenericReturnType();
            this.getOnly = true;
        }
        this.declaringClass = method.getDeclaringClass();
    } else {
        fieldClass = field.getType();
        fieldType = field.getGenericType();
        this.declaringClass = field.getDeclaringClass();
    }
    if (clazz != null && fieldClass == Object.class && (fieldType instanceof TypeVariable)) {
        genericFieldType = getInheritGenericType(clazz, (TypeVariable) fieldType);
        if (genericFieldType != null) {
            this.fieldClass = TypeUtils.getClass(genericFieldType);
            this.fieldType = genericFieldType;
            return;
        }
    }
    genericFieldType = getFieldType(clazz, type, fieldType);
    if (genericFieldType != fieldType) {
        if (genericFieldType instanceof ParameterizedType) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        } else if (genericFieldType instanceof Class) {
            fieldClass = TypeUtils.getClass(genericFieldType);
        }
    }
    this.fieldType = genericFieldType;
    this.fieldClass = fieldClass;
}
 
Example 17
Project: OpenJSharp   File: ReflectionNavigator.java   View Source Code Vote up 4 votes
public Class getDeclaringClassForField(Field field) {
    return field.getDeclaringClass();
}
 
Example 18
Project: backbone   File: AnnotationHelper.java   View Source Code Vote up 4 votes
private static Map<String, AnnotationHolder> getAllColumnAnnotationHoldersInternal(Class<?> cls, String ognl) {
    Collection<Field> fields = ClassUtils.getAllFields(cls);
    Map<String, AnnotationHolder> map = new HashMap<String, AnnotationHolder>();
    if (fields != null && fields.size() > 0) {
        boolean meetPrimaryKey = false;
        for (Field field : fields) {
            Column column = field.getAnnotation(Column.class);
            PrimaryKey primaryKey = field.getAnnotation(PrimaryKey.class);
            if (column != null) {
                AnnotationHolder holder = new AnnotationHolder(field, column, primaryKey, null);
                map.put(field.getName(), holder);
                if (primaryKey != null) {
                    if (meetPrimaryKey) {
                        throw new IllegalArgumentException(String.format("Duplicated primary key @PrimaryKey in(%s)", cls.getCanonicalName()));
                    }
                    meetPrimaryKey = true;
                }
                String refField = column.referenceField();
                boolean found = false;
                if (SqlUtils.isNotBlank(refField)) {
                    Class<?> refClass = field.getDeclaringClass();
                    Collection<Field> refFields = ClassUtils.getAllFields(refClass);
                    if (refFields != null && refFields.size() > 0) {
                        for (Field f : refFields) {
                            if (refField.equals(f.getName())) {
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found) {
                        throw new IllegalArgumentException(String.format("Reference field specified to '%s' but no such field found in %s", column.referenceField(), refClass));
                    }
                }
            } else {
                Component component = field.getAnnotation(Component.class);
                if (component != null) {
                    String comOgnl = ognl;
                    if (comOgnl == null) comOgnl = field.getName();
                    else comOgnl = comOgnl + "." + field.getName();
                    Class<?> comCls = field.getDeclaringClass();
                    Map<String, AnnotationHolder> comMap = getAllColumnAnnotationHoldersInternal(comCls, comOgnl);
                    if (!comMap.isEmpty()) {
                        String[] excludes = component.excludes();
                        if (excludes != null && excludes.length > 0) {
                            List<String> exludeFields = Arrays.asList(excludes);
                            Iterator<Map.Entry<String, AnnotationHolder>> iterator = comMap.entrySet().iterator();
                            while (iterator.hasNext()) {
                                Map.Entry<String, AnnotationHolder> next = iterator.next();
                                if (exludeFields.contains(next.getValue().getField().getName())) iterator.remove();
                            }
                        }
                        map.putAll(comMap);
                    }
                }
            }
        }
    }
    return map;
}
 
Example 19
Project: jsf-sdk   File: JSFExceptionTemplate.java   View Source Code Vote up 4 votes
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void write(Packer pk, T v, boolean required)
		throws IOException {
	if (v == null) {
		if (required) {
			logger.error("Attempted to write null");
			throw new MessageTypeException("Attempted to write null");
		}
		pk.writeNil();
		return;
	}
	Class<?> clazz = v.getClass();
	Field fields[] = CodecUtils.getFields(clazz);
	pk.writeArrayBegin(fields.length + 1);
	pk.write(ClassTypeUtils.getTypeStr(clazz));
	try {
		for(Field f : fields){
			Class<?> fclass = f.getType();
			Class<?> declareClass = f.getDeclaringClass();
			Template fieldTemp = null;
			Object value = readField(v, declareClass, f);
			if(fclass.isArray()){
				Object values[] = null;
				if("stackTrace".equals(f.getName())){
					Method method = declareClass.getDeclaredMethod("getStackTrace");
					Object obj = declareClass.cast(v);
					values = (Object[])method.invoke(obj);
				} else {
					values = (Object[])value;
				}
				if(values == null){
					pk.writeNil();
					continue;
				} else {
					pk.writeArrayBegin(values.length);
					for (Object o : values) {
						if (fieldTemp == null) {
							fieldTemp = this.registerAndGetTemplate(o.getClass());
						}
						fieldTemp.write(pk, o);
					}
				}
			} else {
				if(("cause".equals(f.getName()) && v == value) || fclass.isPrimitive() || value == null){
					pk.writeArrayBegin(1);
					if(fclass.isPrimitive()){
						fieldTemp = this.registerAndGetTemplate(fclass);
						fieldTemp.write(pk, value);
					} else {
						pk.writeNil();
					}
				} else {
					Class<?> valueClass = value.getClass();
					if(valueClass.getName().indexOf("$") > 0){
						pk.writeArrayBegin(0);
					} else {
						pk.writeArrayBegin(2);
						fieldTemp = this.registerAndGetTemplate(valueClass);
						pk.write(ClassTypeUtils.getTypeStr(valueClass));
						fieldTemp.write(pk, value);
					}
				}
			}
			pk.writeArrayEnd();
		}
	} catch(Exception e){
		logger.error("An exception occurred while serializing data: ", e);
		throw new MessageTypeException(clazz.getName() + ":", e);
	}
	pk.writeArrayEnd();
}
 
Example 20
Project: jsf-sdk   File: FieldBean.java   View Source Code Vote up 4 votes
public FieldBean(Field field){
	this.field = field;
	this.field.setAccessible(true);
	this.declareClass = field.getDeclaringClass();
}