下面列出了怎么用com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public List<BeanPropertyDefinition> updateProperties(
DeserializationConfig config, BeanDescription beanDesc,
List<BeanPropertyDefinition> propDefs) {
if (!type.equals(beanDesc.getBeanClass())) {
return propDefs;
}
List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
for (BeanPropertyDefinition propDef : propDefs) {
if (!ignorables.contains(propDef.getName())) {
newPropDefs.add(propDef);
}
}
return newPropDefs;
}
@Override
public List<BeanPropertyDefinition> updateProperties(
DeserializationConfig config, BeanDescription beanDesc,
List<BeanPropertyDefinition> propDefs) {
if (!type.equals(beanDesc.getBeanClass())) {
return propDefs;
}
List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
for (BeanPropertyDefinition propDef : propDefs) {
if (!ignorables.contains(propDef.getName())) {
newPropDefs.add(propDef);
}
}
return newPropDefs;
}
protected void extractAggregatedParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap,
java.lang.reflect.Parameter methodParameter) {
JavaType javaType = TypeFactory.defaultInstance().constructType(methodParameter.getParameterizedType());
BeanDescription beanDescription = Json.mapper().getSerializationConfig().introspect(javaType);
for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
if (!propertyDefinition.couldSerialize()) {
continue;
}
Annotation[] annotations = collectAnnotations(propertyDefinition);
ParameterGenerator propertyParameterGenerator = new ParameterGenerator(method,
methodAnnotationMap,
propertyDefinition.getName(),
annotations,
propertyDefinition.getPrimaryType().getRawClass());
parameterGenerators.add(propertyParameterGenerator);
}
}
private void doCreate() {
JavaType javaType = TypeFactory.defaultInstance().constructType(cls);
BeanDescription beanDescription = JsonUtils.OBJ_MAPPER.getSerializationConfig().introspect(javaType);
for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
if (propertyDefinition.getField() == null) {
continue;
}
if (propertyDefinition.getSetter() == null && !propertyDefinition.getField().isPublic()) {
continue;
}
SetterWrapper setter = propertyDefinition.getSetter() == null ?
new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getField().getAnnotated())) :
new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getSetter().getAnnotated()));
PriorityProperty<?> priorityProperty = createPriorityProperty(propertyDefinition.getField().getAnnotated());
priorityProperty.setCallback((value, target) -> setter.set(target, value), instance);
priorityProperties.add(priorityProperty);
}
}
/**
* Helper method called to indicate problem in POJO (serialization) definitions or settings
* regarding specific property (of a type), unrelated to actual JSON content to map.
* Default behavior is to construct and throw a {@link JsonMappingException}.
*
* @since 2.9
*/
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
String message, Object... msgArgs) throws JsonMappingException {
message = _format(message, msgArgs);
String propName = "N/A";
if (prop != null) {
propName = _quotedString(prop.getName());
}
String beanDesc = "N/A";
if (bean != null) {
beanDesc = ClassUtil.nameOf(bean.getBeanClass());
}
message = String.format("Invalid definition for property %s (of type %s): %s",
propName, beanDesc, message);
throw InvalidDefinitionException.from(getGenerator(), message, bean, prop);
}
private boolean isIncluded(AnnotatedType declaringType, BeanPropertyDefinition prop, boolean deserializableInSubType, InclusionStrategy inclusionStrategy) {
List<AnnotatedElement> elements = Utils.flatten(
Optional.ofNullable(prop.getConstructorParameter()).map(ElementFactory::getParameter),
Optional.ofNullable(prop.getSetter()).map(Annotated::getAnnotated),
Optional.ofNullable(prop.getGetter()).map(Annotated::getAnnotated),
Optional.ofNullable(prop.getField()).map(Annotated::getAnnotated))
.collect(Collectors.toList());
InputFieldInclusionParams params = InputFieldInclusionParams.builder()
.withType(declaringType)
.withElementDeclaringClass(prop.getPrimaryMember().getDeclaringClass())
.withElements(elements)
.withDeserializationInfo(prop.couldDeserialize(), deserializableInSubType)
.build();
return inclusionStrategy.includeInputField(params);
}
private void populateProperties(Class<?> domainType, BusinessEntity entity) {
Map<String, EntityProperty> properties = new HashMap<>();
final PersistentEntity<?, ?> persistentEntity = persistentEntities.getPersistentEntity(domainType);
JacksonMetadata jacksonMetadata = new JacksonMetadata(objectMapper, domainType);
for (BeanPropertyDefinition definition : jacksonMetadata) {
PersistentProperty<?> persistentProperty = persistentEntity.getPersistentProperty(definition.getInternalName());
PropertyFactoryContext context = new PropertyFactoryContext(definition, jacksonMetadata, persistentProperty);
PropertyFactory factory = getFactoryFor(context);
if (factory != null) {
EntityProperty property = factory.create(context);
properties.put(definition.getInternalName(), property);
if(property.isRequired()) {
entity.getRequired().add(definition.getInternalName());
}
}
}
entity.setProperties(properties);
}
@Override
public List<BeanPropertyDefinition> updateProperties(
DeserializationConfig config, BeanDescription beanDesc,
List<BeanPropertyDefinition> propDefs) {
if (!type.equals(beanDesc.getBeanClass())) {
return propDefs;
}
List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
for (BeanPropertyDefinition propDef : propDefs) {
if (!ignorables.contains(propDef.getName())) {
newPropDefs.add(propDef);
}
}
return newPropDefs;
}
private <T> void verifyClazzIsConfigurable(Class<T> clazz)
{
final List<BeanPropertyDefinition> beanDefs = jsonMapper.getSerializationConfig()
.introspect(jsonMapper.constructType(clazz))
.findProperties();
for (BeanPropertyDefinition beanDef : beanDefs) {
final AnnotatedField field = beanDef.getField();
if (field == null || !field.hasAnnotation(JsonProperty.class)) {
throw new ProvisionException(
String.format(
"JsonConfigurator requires Jackson-annotated Config objects to have field annotations. %s doesn't",
clazz
)
);
}
}
}
private static Set<String> getJsonProperties(Type type)
{
ObjectMapper mapper = new ObjectMapperProvider().get();
return mapper.getSerializationConfig()
.introspect(mapper.getTypeFactory().constructType(type))
.findProperties()
.stream()
.map(BeanPropertyDefinition::getName)
.collect(toImmutableSet());
}
private void resolveBeanPropertyDefinition(ModelPropertyContext context) {
BeanPropertyDefinition beanPropertyDefinition = context.getBeanPropertyDefinition().orNull();
if (beanPropertyDefinition == null) {
return;
}
if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotNull.class).isPresent()) {
context.getBuilder().required(true);
} else if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotEmpty.class).isPresent()) {
context.getBuilder().required(true);
} else if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotBlank.class).isPresent()) {
context.getBuilder().required(true);
} else {
context.getBuilder().required(false);
}
}
@Override
public void apply(ModelPropertyContext context) {
BeanPropertyDefinition definition = context.getBeanPropertyDefinition().orNull();
if (definition == null) {
return;
}
Class<?> modelClass = definition.getAccessor().getDeclaringClass();
Field field = definition.getField().getAnnotated();
if (!modelClass.isAnnotationPresent(ApiModel.class)) {
return;
}
resolveDescription(context, field);
resolveMapEnum(context, field);
resolveExample(context, modelClass, field);
}
@Override
public void serialize(HalEntityWrapper wrapper, JsonGenerator generator, SerializerProvider serializers)
throws IOException {
generator.writeStartObject();
for (BeanPropertyDefinition property : getPropertyDefinitions(serializers, wrapper.getEntity().getClass())) {
AnnotatedMember accessor = property.getAccessor();
if (accessor != null) {
writeValue(property.getName(), accessor.getValue(wrapper.getEntity()), generator);
}
}
writeLinks(wrapper.getEntity(), generator);
generator.writeEndObject();
}
private List<BeanPropertyDefinition> getPropertyDefinitions(SerializerProvider serializers, Class<?> entityClass) {
JavaType entityType = serializers.getTypeFactory().constructType(entityClass);
return new BasicClassIntrospector()
.forSerialization(serializers.getConfig(), entityType, serializers.getConfig())
.findProperties();
}
public static Annotation[] collectAnnotations(BeanPropertyDefinition propertyDefinition) {
List<Annotation> annotations = new ArrayList<>();
if (propertyDefinition.getField() != null) {
Collections.addAll(annotations, propertyDefinition.getField().getAnnotated().getAnnotations());
}
if (propertyDefinition.getGetter() != null) {
Collections.addAll(annotations, propertyDefinition.getGetter().getAnnotated().getAnnotations());
}
if (propertyDefinition.getSetter() != null) {
Collections.addAll(annotations, propertyDefinition.getSetter().getAnnotated().getAnnotations());
}
return annotations.toArray(new Annotation[annotations.size()]);
}
@Override
protected void processBeanParameter(int producerParamIdx, Parameter producerParameter) {
ProducerBeanParamMapper mapper = new ProducerBeanParamMapper(
providerMethod.getParameters()[producerParamIdx].getName(), producerParameter.getType());
JavaType producerType = TypeFactory.defaultInstance().constructType(producerParameter.getParameterizedType());
for (BeanPropertyDefinition propertyDefinition : serializationConfig.introspect(producerType)
.findProperties()) {
String parameterName = collectParameterName(providerMethod, propertyDefinition);
Integer swaggerIdx = findSwaggerParameterIndex(parameterName);
if (swaggerIdx == null) {
throw new IllegalStateException(String
.format("failed to find producer parameter in contract, method=%s:%s, bean parameter name=%s.",
providerMethod.getDeclaringClass().getName(), providerMethod.getName(), parameterName));
}
Setter<Object, Object> setter;
if (propertyDefinition.hasSetter()) {
setter = LambdaMetafactoryUtils.createLambda(propertyDefinition.getSetter().getAnnotated(), Setter.class);
} else {
setter = LambdaMetafactoryUtils.createSetter(propertyDefinition.getField().getAnnotated());
}
swaggerParameterTypes.put(parameterName, propertyDefinition.getPrimaryType());
mapper.addField(parameterName, setter);
processedSwaggerParamters.add(parameterName);
}
mappers.add(mapper);
}
protected void processBeanParameter(int consumerParamIdx, java.lang.reflect.Parameter consumerParameter) {
ConsumerBeanParamMapper mapper = new ConsumerBeanParamMapper(
this.providerMethod.getParameters()[consumerParamIdx].getName());
JavaType consumerType = TypeFactory.defaultInstance().constructType(consumerParameter.getParameterizedType());
for (BeanPropertyDefinition propertyDefinition : serializationConfig.introspect(consumerType).findProperties()) {
String parameterName = collectParameterName(providerMethod, propertyDefinition);
Integer swaggerIdx = findSwaggerParameterIndex(parameterName);
if (swaggerIdx == null) {
// unknown field, ignore it
LOGGER.warn(
"new consumer invoke old version producer, bean parameter({}) is not exist in contract, method={}:{}.",
parameterName, providerMethod.getDeclaringClass().getName(), providerMethod.getName());
continue;
}
Getter<Object, Object> getter;
if (propertyDefinition.hasGetter()) {
getter = LambdaMetafactoryUtils.createLambda(propertyDefinition.getGetter().getAnnotated(), Getter.class);
} else {
getter = LambdaMetafactoryUtils.createGetter(propertyDefinition.getField().getAnnotated());
}
mapper.addField(parameterName, getter);
processedSwaggerParamters.add(parameterName);
}
mappers.add(mapper);
}
@SuppressWarnings("unchecked")
public static <T> T initGetter(BeanPropertyDefinition propertyDefinition) {
if (propertyDefinition.hasGetter()) {
return LambdaMetafactoryUtils.createGetter(propertyDefinition.getGetter().getAnnotated());
}
if (propertyDefinition.hasField() && propertyDefinition.getField().isPublic()) {
return (T) LambdaMetafactoryUtils.createGetter(propertyDefinition.getField().getAnnotated());
}
return null;
}
protected Object initSetter(BeanPropertyDefinition propertyDefinition) {
if (propertyDefinition.hasSetter()) {
return LambdaMetafactoryUtils.createSetter(propertyDefinition.getSetter().getAnnotated());
}
if (propertyDefinition.hasField() && propertyDefinition.getField().isPublic()) {
return LambdaMetafactoryUtils.createSetter(propertyDefinition.getField().getAnnotated());
}
return null;
}
private String getJavaBeanPropertyName(JavaBeanProperty property) {
ObjectMapper objectMapper = DatabindCodec.mapper();
JavaType type = objectMapper.constructType(property.getDeclaringClass());
BeanDescription desc = objectMapper.getSerializationConfig().introspect(type);
return desc.findProperties()
.stream()
.filter(prop -> prop.getInternalName().equals(property.getName()))
.map(BeanPropertyDefinition::getName)
.findFirst()
.orElse(property.getName());
}
@Override
public Object includeFilterInstance(BeanPropertyDefinition forProperty,
Class<?> filterClass)
{
if (filterClass == null) {
return null;
}
HandlerInstantiator hi = _config.getHandlerInstantiator();
Object filter = (hi == null) ? null : hi.includeFilterInstance(_config, forProperty, filterClass);
if (filter == null) {
filter = ClassUtil.createInstance(filterClass,
_config.canOverrideAccessModifiers());
}
return filter;
}
protected AttributePropertyWriter(String attrName, BeanPropertyDefinition propDef,
Annotations contextAnnotations, JavaType declaredType,
JsonInclude.Value inclusion)
{
super(propDef, contextAnnotations, declaredType,
/* value serializer */ null, /* type serializer */ null, /* ser type */ null,
inclusion,
// 10-Oct-2016, tatu: Could enable per-view settings too in future
null);
_attrName = attrName;
}
public static AttributePropertyWriter construct(String attrName,
BeanPropertyDefinition propDef,
Annotations contextAnnotations,
JavaType declaredType)
{
return new AttributePropertyWriter(attrName, propDef,
contextAnnotations, declaredType);
}
public static CreatorCandidate construct(AnnotationIntrospector intr,
AnnotatedWithParams creator, BeanPropertyDefinition[] propDefs)
{
final int pcount = creator.getParameterCount();
Param[] params = new Param[pcount];
for (int i = 0; i < pcount; ++i) {
AnnotatedParameter annParam = creator.getParameter(i);
JacksonInject.Value injectId = intr.findInjectableValue(annParam);
params[i] = new Param(annParam, (propDefs == null) ? null : propDefs[i], injectId);
}
return new CreatorCandidate(intr, creator, params, pcount);
}
public PropertyName paramName(int i) {
BeanPropertyDefinition propDef = _params[i].propDef;
if (propDef != null) {
return propDef.getFullName();
}
return null;
}
public PropertyName explicitParamName(int i) {
BeanPropertyDefinition propDef = _params[i].propDef;
if (propDef != null) {
if (propDef.isExplicitlyNamed()) {
return propDef.getFullName();
}
}
return null;
}
public Param(AnnotatedParameter p, BeanPropertyDefinition pd,
JacksonInject.Value i)
{
annotated = p;
propDef = pd;
injection = i;
}
public FieldProperty(BeanPropertyDefinition propDef, JavaType type,
TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedField field)
{
super(propDef, type, typeDeser, contextAnnotations);
_annotated = field;
_field = field.getAnnotated();
_skipNulls = NullsConstantProvider.isSkipper(_nullProvider);
}
public SetterlessProperty(BeanPropertyDefinition propDef, JavaType type,
TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedMethod method)
{
super(propDef, type, typeDeser, contextAnnotations);
_annotated = method;
_getter = method.getAnnotated();
}
protected InvalidDefinitionException(JsonParser p, String msg,
BeanDescription bean, BeanPropertyDefinition prop) {
super(p, msg);
_type = (bean == null) ? null : bean.getType();
_beanDesc = bean;
_property = prop;
}