/** * Report an error due to a difference in on of the fields of an event. * * @param eventType The (runtime) type of event the difference was found in * @param field The field that contains the difference * @param actual The actual value of the field * @param expected The expected value of the field */ public void reportDifferentEventContents( Class<?> eventType, Field field, Object actual, Object expected) { StringBuilder sb = new StringBuilder("One of the events contained different values than expected"); sb.append(NEWLINE) .append(NEWLINE) .append("In an event of type [") .append(eventType.getSimpleName()) .append("], the property [") .append(field.getName()) .append("] "); if (!eventType.equals(field.getDeclaringClass())) { sb.append("(declared in [").append(field.getDeclaringClass().getSimpleName()).append("]) "); } sb.append("was not as expected.") .append(NEWLINE) .append("Expected <") // NOSONAR .append(nullSafeToString(expected)) .append("> but got <") .append(nullSafeToString(actual)) .append(">") .append(NEWLINE); throw new AxonAssertionError(sb.toString()); }
@Override public Object processAnnotation(final SystemProperty systemProperty, final Field field) throws AnnotationProcessingException { String key = systemProperty.value().trim(); // check attribute rejectIfEmpty(key, missingAttributeValue("value", SystemProperty.class.getName(), field)); // check system property String value = System.getProperty(key); if (value == null) { LOGGER.log( Level.WARNING, "System property ''{0}'' on field ''{1}'' of type ''{2}'' not found in system properties: {3}", new Object[] { key, field.getName(), field.getDeclaringClass().getName(), System.getProperties() }); // Use default value if specified String defaultValue = systemProperty.defaultValue(); if (defaultValue != null && !defaultValue.isEmpty()) { value = defaultValue.trim(); } else { LOGGER.log( Level.WARNING, "Default value of system property ''{0}'' on field ''{1}'' of type ''{2}'' is empty", new Object[] {key, field.getName(), field.getDeclaringClass().getName()}); return null; } } return value; }
/** Super before subclass, alphabetical within a given class */ public int compare(Object o1, Object o2) { Field f1 = (Field) o1; Field f2 = (Field) o2; if (f1 == f2) return 0; if (f1.getDeclaringClass() == f2.getDeclaringClass()) return f1.getName().compareTo(f2.getName()); if (f1.getDeclaringClass().isAssignableFrom(f2.getDeclaringClass())) return -1; return 1; }
@Test public void testFieldDeclaringType() throws Exception { assertThat( describe(first).getDeclaringType(), is((GenericTypeDescription) new TypeDescription.ForLoadedType(first.getDeclaringClass()))); assertThat( describe(second).getDeclaringType(), is((GenericTypeDescription) new TypeDescription.ForLoadedType(second.getDeclaringClass()))); }
/** * Searches for {@link URLQueryParameter} annotations on a single field. * * @param field Field to scan * @param classMappingIds The mapping IDs of the class this method belongs to */ private void processFieldAnnotations(final Field field, final String[] classMappingIds) { // Is there a @URLQueryParameter annotation? URLQueryParameter queryParamAnnotation = field.getAnnotation(URLQueryParameter.class); if (queryParamAnnotation != null) { // create a QueryParamSpec from the annotation QueryParamSpec queryParam = new QueryParamSpec(); queryParam.setFieldName(field.getName()); queryParam.setOwnerClass(field.getDeclaringClass()); queryParam.setName(queryParamAnnotation.value()); queryParam.setOnPostback(queryParamAnnotation.onPostback()); // check which mapping the action belongs to if (!isBlank(queryParamAnnotation.mappingId())) { // action belongs to the mapping mentioned with mappingId attribute queryParam.setMappingIds(new String[] {queryParamAnnotation.mappingId().trim()}); } else if ((classMappingIds != null) && (classMappingIds.length > 0)) { // use the mappings found on the class queryParam.setMappingIds(classMappingIds); } else { throw new IllegalArgumentException( "Unable to find a suitable mapping " + "for the query-parameter definied on field '" + field.getName() + "' in class '" + field.getDeclaringClass().getName() + "'. Either place a @URLMapping annotation on the " + "class or reference a foreign mapping using the 'mappingId' attribute."); } // check if there is also a validation annotation placed on the field URLValidator validationAnnotation = field.getAnnotation(URLValidator.class); // check if annotation has been found if (validationAnnotation != null) { // set validation options on the QueryParamSpec object queryParam.setValidatorIds(validationAnnotation.validatorIds()); queryParam.setOnError(validationAnnotation.onError()); queryParam.setValidator(validationAnnotation.validator()); } // check if there is also a converter annotation placed on the field URLConverter converterAnnotation = field.getAnnotation(URLConverter.class); if (converterAnnotation != null) { queryParam.setConverterId(converterAnnotation.converterId().trim()); } // add the new spec object to the list of specs queryParamList.add(queryParam); } }
private void jitFieldAccessInvocation( FieldAccessInvocation invocation, Class<?> currentClass, boolean firstInvocation) { Field field = invocation.getField(); boolean isStatic = (field.getModifiers() & Modifier.STATIC) != 0; if (firstInvocation && !isStatic) { mv.visitVarInsn(ALOAD, 1); } if (!isStatic && !field.getDeclaringClass().isAssignableFrom(currentClass)) { cast(field.getDeclaringClass()); } readField(field); }
public void printAll(Class c) { Constructor[] cs = this.getAllConstructorsFromClass(c); System.out.println(" Constructors:"); for (Constructor constructor : cs) { System.out.print(" " + constructor); if (constructor.getDeclaringClass() != c) System.out.println(" (inherited from " + constructor.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Methods:"); Method[] ms = this.getAllMethodsFromClass(c); for (Method method : ms) { System.out.print(" " + method); if (method.getDeclaringClass() != c) System.out.println(" (inherited from " + method.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Classes:"); Class[] cls = this.getClassesFromClass(c); for (Class class1 : cls) { System.out.println(" " + class1); } System.out.println(" Fields:"); Field[] fs = this.getFieldsFromClass(c); for (Field field : fs) { System.out.print(" " + field); if (field.getDeclaringClass() != c) System.out.println(" (inherited from " + field.getDeclaringClass().getName() + ")"); else System.out.println(); } System.out.println(" Interfaces:"); Class[] is = this.getInterfacesFromClass(c); for (Class class2 : is) { System.out.println(" " + class2); } System.out.println(" Local Methods:"); Method[] mls = this.getLocalMethodsFromClass(c); for (Method method2 : mls) { System.out.print(" " + method2); if (method2.getDeclaringClass() != c) System.out.println(" (inherited from " + method2.getDeclaringClass().getName() + ")"); else System.out.println(); } }
public int compare(Field a, Field b) { if (a == b) return 0; else if (a == null) return -1; else if (b == null) return 1; else if (a.equals(b)) return 0; int cmp = a.getName().compareTo(b.getName()); if (cmp != 0) return cmp; cmp = a.getDeclaringClass().getName().compareTo(b.getDeclaringClass().getName()); if (cmp != 0) return cmp; return a.getType().getName().compareTo(b.getType().getName()); }
public TypeBinding getTypeBinding(Field field) { Class itsType = field.getType(); if (this.isIgnored(field)) { return new NoopTypeBinding(field); } else if (List.class.isAssignableFrom(itsType)) { Class listType = getTypeArgument(field); if (listType == null) { Logs.extreme() .debug( String.format( "IGNORE: %-70s [type=%s] NO GENERIC TYPE FOR LIST\n", field.getDeclaringClass().getCanonicalName() + "." + field.getName(), listType)); return new NoopTypeBinding(field); } else if (this.typeBindings.containsKey(listType.getCanonicalName())) { return new CollectionTypeBinding( field.getName(), this.typeBindings.get(listType.getCanonicalName())); } else if (BindingFileSearch.INSTANCE.MSG_DATA_CLASS.isAssignableFrom(listType)) { return new CollectionTypeBinding( field.getName(), new ObjectTypeBinding(field.getName(), listType)); } else { Logs.extreme() .debug( String.format( "IGNORE: %-70s [type=%s] LIST'S GENERIC TYPE DOES NOT CONFORM TO EucalyptusData\n", field.getDeclaringClass().getCanonicalName() + "." + field.getName(), listType.getCanonicalName())); return new NoopTypeBinding(field); } } else if (this.typeBindings.containsKey(itsType.getCanonicalName())) { TypeBinding t = this.typeBindings.get(itsType.getCanonicalName()); try { t = this.typeBindings.get(itsType.getCanonicalName()).getClass().newInstance(); } catch (Exception e) { } return t.value(field.getName()); } else if (BindingFileSearch.INSTANCE.MSG_DATA_CLASS.isAssignableFrom(field.getType())) { return new ObjectTypeBinding(field); } else { Logs.extreme() .debug( String.format( "IGNORE: %-70s [type=%s] TYPE DOES NOT CONFORM TO EucalyptusData\n", field.getDeclaringClass().getCanonicalName() + "." + field.getName(), field.getType().getCanonicalName())); return new NoopTypeBinding(field); } }
private void bindItem(final Binder binder, final SpaceIndexItem<Extension, ?> item) throws InstantiationException { switch (item.kind()) { case TYPE: { final Class impl = (Class) item.element(); binder.bind(impl).in(Scopes.SINGLETON); bindHierarchy(binder, Key.get(impl)); break; } case METHOD: { final Method method = (Method) item.element(); final String name = method.getDeclaringClass().getName() + '.' + method.getName(); final ExtensionQualifier qualifier = new ExtensionQualifierImpl(item.annotation(), name); bindProvider(binder, item, Key.get(method.getReturnType(), qualifier)); break; } case FIELD: { final Field field = (Field) item.element(); final String name = field.getDeclaringClass().getName() + '.' + field.getName(); final ExtensionQualifier qualifier = new ExtensionQualifierImpl(item.annotation(), name); bindProvider(binder, item, Key.get(field.getType(), qualifier)); break; } default: break; } }
public OJField getCopy() { /*if (isAlterable()) return substance.getCopy();*/ /** **************** */ // return (FieldDeclaration) substance.clone () ; try { if (substance instanceof OJFieldByteCode) { java.lang.reflect.Field field = ((OJFieldByteCode) substance).getByteCode(); OJField result = (OJField) this.clone(); // On remplace du ByteCode par du SourceCode FieldDeclaration fd = new FieldDeclaration( new ModifierList(field.getModifiers()), TypeName.forOJClass(OJClass.forClass(field.getDeclaringClass())), field.getName(), null); Environment env = substance.getDeclaringClass().getEnvironment(); result.substance = new OJFieldSourceCode(env, substance.getDeclaringClass(), fd); return result; } else if (substance instanceof OJFieldSourceCode) { OJField result = (OJField) this.clone(); result.substance = new OJFieldSourceCode( ((OJFieldSourceCode) this.substance).getEnvironment(), this.substance.getDeclaringClass(), (FieldDeclaration) this.substance.getSourceCode().makeRecursiveCopy()); return result; } } catch (Exception e) { System.err.println("Failed to copy " + this + ": " + e); e.printStackTrace(); } return null; }
/** * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the * object's size measured so far. <code>f</code> is the field being probed. * * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code> * field's offset and representation size (unaligned). */ private static long adjustForField(long sizeSoFar, final Field f) { final Class<?> type = f.getType(); final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF; if (objectFieldOffsetMethod != null) { try { final long offsetPlusSize = ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize; return Math.max(sizeSoFar, offsetPlusSize); } catch (IllegalAccessException ex) { throw new RuntimeException("Access problem with sun.misc.Unsafe", ex); } catch (InvocationTargetException ite) { final Throwable cause = ite.getCause(); if (cause instanceof RuntimeException) throw (RuntimeException) cause; if (cause instanceof Error) throw (Error) cause; // this should never happen (Unsafe does not declare // checked Exceptions for this method), but who knows? throw new RuntimeException( "Call to Unsafe's objectFieldOffset() throwed " + "checked Exception when accessing field " + f.getDeclaringClass().getName() + "#" + f.getName(), cause); } } else { // TODO: No alignments based on field type/ subclass fields alignments? return sizeSoFar + fsize; } }
private ArrayList<Element> serializeFields( Field[] fields, Object object, Document doc) // serializes the fields { Class currentClass = object.getClass(); ArrayList<Element> elements = new ArrayList<Element>(); for (Field f : fields) { try { if (!f.getType().isPrimitive()) // Field not primitive, is a reference to another object { } else // field is primitive { Element newField = new Element("field"); newField.setAttribute("name", f.getName()); newField.setAttribute("declaringclass", f.getDeclaringClass().getName()); Element newValue = new Element("value"); newValue.addContent(f.get(object).toString()); newField.addContent(newValue); elements.add(newField); } } catch (Exception e) { e.printStackTrace(); } } return elements; }
@Override public void prepareTestInstance(TestContext context) { List<Field> mocks = context.introspector().selectFields(fieldsAnnotatedBy(Mock.class)); Mockery mockery = findProvidedMockery(context); if (mockery == null) { mockery = new Mockery(); for (Field mock : mocks) { if (!mock.getType().isInterface()) { mockery.setImposteriser(ClassImposteriser.INSTANCE); break; } } } context.attributes().set(MOCKERY, mockery); for (Field field : context .introspector() .selectFields( and(fieldsAccepting(Mockery.class), fieldsAnnotatedBy(MockContext.class)))) { context.introspector().set(field, mockery); } for (Field field : mocks) { context .introspector() .set( field, mockery.mock( field.getType(), field.getDeclaringClass().getName() + "." + field.getName())); } }
public String process() { if (this.type.getCanonicalName() == null) { new RuntimeException("" + this.type).printStackTrace(); } else { this.elem(Elem.mapping); if (this.abs) { this.attr("abstract", "true"); } else { this.attr("name", this.type.getSimpleName()) .attr("extends", this.type.getSuperclass().getCanonicalName()); } this.attr("class", this.type.getCanonicalName()); if (BindingGenerator.MSG_TYPE.isAssignableFrom(this.type.getSuperclass()) || BindingGenerator.DATA_TYPE.isAssignableFrom(this.type.getSuperclass())) { this.elem(Elem.structure) .attr("map-as", this.type.getSuperclass().getCanonicalName()) .end(); } for (Field f : type.getDeclaredFields()) { TypeBinding tb = getTypeBinding(f); if (!(tb instanceof NoopTypeBinding)) { System.out.printf( "BOUND: %-70s [type=%s:%s]\n", f.getDeclaringClass().getCanonicalName() + "." + f.getName(), tb.getTypeName(), f.getType().getCanonicalName()); this.append(tb.toString()); } } this.end(); } return this.toString(); }
@Override public void enrich(final SearchContext searchContext, Object target) { Collection<Field> fields = ReflectionHelper.getFieldsWithAnnotation(target.getClass(), JavaScript.class); for (Field field : fields) { GrapheneContext grapheneContext = searchContext == null ? null : ((GrapheneProxyInstance) searchContext).getGrapheneContext(); if (grapheneContext == null) { grapheneContext = GrapheneContext.getContextFor(ReflectionHelper.getQualifier(field.getAnnotations())); } if (!field.isAccessible()) { field.setAccessible(true); } try { field.set(target, JSInterfaceFactory.create(grapheneContext, field.getType())); } catch (Exception e) { throw new IllegalStateException( "Can't inject value to the field '" + field.getName() + "' declared in class '" + field.getDeclaringClass().getName() + "'", e); } } }
/* * TODO: Profiling shows that the reflection and conditional logic in this * method is a hotspot. This could be remedied by generating synthetic * InstantiateCommand types that initialize themselves. */ private IdentityValueCommand makeObject(Class<?> type, Object value) throws SerializationException { if (type.isAnonymousClass() || type.isLocalClass()) { throw new SerializationException("Cannot serialize anonymous or local classes"); } Class<?> manualType = type; Class<?> customSerializer; do { customSerializer = SerializabilityUtil.hasCustomFieldSerializer(manualType); if (customSerializer != null) { break; } manualType = manualType.getSuperclass(); } while (manualType != null); IdentityValueCommand ins; if (customSerializer != null) { ins = serializeWithCustomSerializer(customSerializer, value, type, manualType); } else { ins = new InstantiateCommand(type); identityMap.put(value, ins); } /* * If we're looking at a subclass of a manually-serialized type, the * subclass must be tagged as serializable in order to qualify for * serialization. */ if (type != manualType) { if (!Serializable.class.isAssignableFrom(type) && !IsSerializable.class.isAssignableFrom(type)) { throw new SerializationException(type.getName() + " is not a serializable type"); } } while (type != manualType) { Field[] serializableFields = clientOracle.getOperableFields(type); for (Field declField : serializableFields) { assert (declField != null); Accessor accessor = CommandSerializationUtil.getAccessor(declField.getType()); ValueCommand valueCommand; Object fieldValue = accessor.get(value, declField); if (fieldValue == null) { valueCommand = NullValueCommand.INSTANCE; } else { Class<? extends Object> fieldType = declField.getType().isPrimitive() ? declField.getType() : fieldValue.getClass(); valueCommand = makeValue(fieldType, fieldValue); } ((HasSetters) ins).set(declField.getDeclaringClass(), declField.getName(), valueCommand); } type = type.getSuperclass(); } return ins; }
/** 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 */ 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); } }
public static <X> String createFieldId(Field field, Collection<Annotation> annotations) { StringBuilder builder = new StringBuilder(); builder.append(field.getDeclaringClass().getName()); builder.append('.'); builder.append(field.getName()); builder.append(createAnnotationCollectionId(annotations)); return builder.toString(); }
@SuppressWarnings("unused") private static String getHelpFor(Field f) { return "Set the field " + f.getName() + " of " + f.getDeclaringClass() + " (see javadoc for details)."; }
public static Method getSetMethod(Field field) { if (field == null) { return null; } String name = getSetName(field.getName()); Class clazz = field.getDeclaringClass(); return getMethod(name, field.getType(), clazz); }
/** * Returns the resolved generic type of {@code field}. * * @param field a field defined by this or any superclass. * @since 2.0 */ public TypeLiteral<?> getFieldType(Field field) { Assert.checkArgument( field.getDeclaringClass().isAssignableFrom(rawType), "%s is not defined by a supertype of %s", field, type); return resolve(field.getGenericType()); }
public IllegalFlagAnnotationException(Field field) { super( "field: " + field.toGenericString() + " from " + field.getDeclaringClass() + " cannot be annotated with " + FlagInfo.class); }
public static Reference createFor(PersistenceContext persistenceContext, Field field) { final String name; if (persistenceContext.name().length() > 0) { name = persistenceContext.name(); } else { name = field.getDeclaringClass().getName() + "/" + field.getName(); } return new Reference(EntityManager.class, name, field); }
private void bindAutoBindFields() { for (Field field : classpathScanner.getFields()) { if (ignoreClasses.contains(field.getDeclaringClass())) { continue; } bindAnnotations(field.getDeclaredAnnotations()); } }
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); }
/** * Creates a new proxy for the given key. * * @throws NotSerializableException If the given key is not declared as a static constant in its * {@linkplain Class#getEnclosingClass() enclosing class}. */ SerializedKey(final RenderingHints.Key key) throws NotSerializableException { final Field f = Hints.fieldOf(key); if (f == null) { throw new NotSerializableException( Errors.format(Errors.Keys.UnknownType_1, Classes.getShortClassName(key))); } definer = f.getDeclaringClass(); field = f.getName(); }
public FieldOptionElement( Field field, String optionName, Option option, Class<?> optionType, ValueAwareNotationParser<?> notationParser) { super(optionName, option, optionType, field.getDeclaringClass(), notationParser); this.field = field; getSetter(); }
/** * Create a name for the given reflected field. The resulting name will be in a resolved state. */ public MemberName(Field fld) { init( fld.getDeclaringClass(), fld.getName(), fld.getType(), flagsMods(IS_FIELD, fld.getModifiers())); // fill in vmtarget, vmindex while we have fld in hand: MethodHandleNatives.init(this, fld); assert (isResolved()); }
private static Class<?> getElementType(Type type, Field field) { if (type instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; } throw new IllegalStateException( String.format( "Unsupported type(%s) of field(%s) of %s, use List instead!", type, field.getName(), field.getDeclaringClass())); }