private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) { ObjectMapper mapper = new ObjectMapper(mapping); mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class); mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class); mapper.addMixIn(Config.class, ConfigMixIn.class); mapper.addMixIn(CodecProvider.class, ClassMixIn.class); mapper.addMixIn(ResolverProvider.class, ClassMixIn.class); mapper.addMixIn(Codec.class, ClassMixIn.class); mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class); mapper.addMixIn(LoadBalancer.class, ClassMixIn.class); FilterProvider filterProvider = new SimpleFilterProvider() .addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept()); mapper.setFilterProvider(filterProvider); mapper.setSerializationInclusion(Include.NON_NULL); if (classLoader != null) { TypeFactory tf = TypeFactory.defaultInstance() .withClassLoader(classLoader); mapper.setTypeFactory(tf); } return mapper; }
@Override public ListResult<T> fetchAll() { try { // get the data out.. byte[] json = jsondb.getAsByteArray(getCollectionPath()); if( json!=null && json.length > 0 ) { // Lets use jackson to parse the map of keys to our model instances ObjectMapper mapper = Json.mapper(); TypeFactory typeFactory = mapper.getTypeFactory(); MapType mapType = typeFactory.constructMapType(LinkedHashMap.class, String.class, getType()); LinkedHashMap<String, T> map = mapper.readValue(json, mapType); return ListResult.of(map.values()); } return ListResult.of(Collections.<T>emptyList()); } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException|IOException e) { throw SyndesisServerException.launderThrowable(e); } }
/** * Constructs the object based on the content as a List, the JSON can be an array or just a single value without the [] symbols * @param content Reader * @return A collection of the specified type */ public <T> List<T> constructList(Reader content, Class<T> requiredType) { ObjectReader reader = objectMapper.readerFor(TypeFactory.defaultInstance().constructParametricType(List.class, requiredType)); try { List<T> toReturn = reader.readValue(content); if (toReturn == null || toReturn.isEmpty()) { throw new InvalidArgumentException("Could not read content from HTTP request body, the list is empty"); } return toReturn; } catch (IOException error) { throw new InvalidArgumentException("Could not read content from HTTP request body: "+error.getMessage()); } }
private JsonDeserializer<io.redlink.smarti.model.config.Configuration > buildConfigurationDeserializer(ObjectMapper objectMapper) { return new JsonDeserializer<io.redlink.smarti.model.config.Configuration>() { @Override public io.redlink.smarti.model.config.Configuration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { final TypeFactory tf = ctxt.getTypeFactory(); final MapLikeType smartiConfigType = tf.constructMapLikeType(Map.class, tf.constructType(String.class), tf.constructCollectionLikeType(List.class, ComponentConfiguration.class)); final io.redlink.smarti.model.config.Configuration configuration = new io.redlink.smarti.model.config.Configuration(); configuration.setConfig(objectMapper.readerFor(smartiConfigType).readValue(p, smartiConfigType)); return configuration; } }; }
@SuppressWarnings( "unchecked" ) public static < K, V > Map< K, V > fromJsonAsMap ( String jsonToken, Class< K > typeClassK, Class< V > typeClassV ) { Map< K, V > asMap = null; try { JavaType collectionType = TypeFactory .defaultInstance () .constructMapType ( Map.class, typeClassK, typeClassV ); asMap = mapper.readValue ( jsonToken, collectionType ); } catch ( IOException e ) { e.printStackTrace (); } return asMap; }
public static <T> List<T> getBeanCollectionFromJsonString( String json, Class<T> class_name ) { List<T> contents = null; try { contents = getDefaultMapper().readValue( json, TypeFactory.defaultInstance().constructCollectionType( List.class, class_name ) ); } catch ( IOException e ) { logger.error( "Exception in getBeanCollectionFromJsonString", e ); } return contents; }
private JavaType tryMatchRedfishResource( String id ) { Matcher resourceMatcher = REDFISH_RESOURCE.matcher( id ); if ( resourceMatcher.matches() ) { try { String redfishResourceClassName = getClassName( resourceMatcher.group( REDFISH_RESOURCE_NAME_GROUP ) ); Class detectedClass = Class.forName( redfishResourceClassName ); return TypeFactory.defaultInstance().constructSpecializedType( baseType, detectedClass ); } catch ( ClassNotFoundException e ) { throw new UnsupportedOperationException( "Could not determine class to deserialize into for \"@odata.type\": \"" + id + "\"" ); } } return null; }
@Test public void testExtraction() throws Exception { Message<?> received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS); assertNotNull(received); assertThat(received.getPayload(), Matchers.instanceOf(String.class)); CollectionLikeType valueType = TypeFactory.defaultInstance() .constructCollectionLikeType(List.class, Map.class); List<Map<?, ?>> payload = this.objectMapper.readValue((String) received.getPayload(), valueType); assertEquals(3, payload.size()); assertEquals(1, payload.get(0).get("ID")); assertEquals("John", payload.get(2).get("NAME")); }
@Test public void testExtraction() throws Exception { Message<?> received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS); assertNotNull(received); assertThat(received.getPayload(), Matchers.instanceOf(String.class)); CollectionLikeType valueType = TypeFactory.defaultInstance() .constructCollectionLikeType(List.class, Map.class); List<Map<?, ?>> payload = this.objectMapper.readValue((String) received.getPayload(), valueType); assertEquals(2, payload.size()); assertEquals(1, payload.get(0).get("ID")); assertEquals(2, payload.get(1).get("ID")); received = messageCollector.forChannel(source.output()).poll(10, TimeUnit.SECONDS); assertNotNull(received); payload = this.objectMapper.readValue((String) received.getPayload(), valueType); assertEquals(1, payload.size()); assertEquals(3, payload.get(0).get("ID")); }
/** * Helper method for deserializing a chat JSON response to a collection of objects. * * @param jsonStr * The chat JSON response. * @param mapElement * Chat JSON responses are actually maps with a single element. This argument is * the value of the element to pull out from the map. * @param colClassElements * The types of objects that the collection object will contain. * @param objMapper * The JSON object mapper used to deserialize the JSON string. * @return A collection of elements of type <code>colClassElements</code>. */ private <T> Collection<T> deserializeJsonStr(String jsonStr, String mapElement, Class<T> colClassElements, ObjectMapper objMapper) { Map<String, Collection<T>> re; try { TypeFactory typeFactory = objMapper.getTypeFactory(); CollectionType type = typeFactory.constructCollectionType(List.class, colClassElements); MapType thetype = typeFactory.constructMapType(HashMap.class, typeFactory.constructType(String.class), type); re = objMapper.readValue(jsonStr, thetype); } catch (IOException e) { LOG.error("Got exception when trying to deserialize list of {}", colClassElements, e); return Lists.newArrayListWithExpectedSize(0); } return re.get(mapElement); }
@Override public <T> Optional<T> getPropertyAs(final String name, final Type type) throws IllegalArgumentException { final Optional<String> property = getProperty(name); if (!property.isPresent()) { return Optional.empty(); } try { final TypeFactory typeFactory = _objectMapper.getTypeFactory(); @SuppressWarnings("unchecked") final Optional<T> value = Optional.ofNullable((T) _objectMapper.readValue( property.get(), typeFactory.constructType(type))); return value; } catch (final IOException e) { throw new IllegalArgumentException( String.format( "Unable to construct object from configuration; name=%s, type=%s, property=%s", name, type, property), e); } }
@Override public <T> Optional<T> getAs(final Type type) throws IllegalArgumentException { final Optional<JsonNode> property = getJsonSource().getValue(); if (!property.isPresent()) { return Optional.empty(); } try { final TypeFactory typeFactory = _objectMapper.getTypeFactory(); @SuppressWarnings("unchecked") final Optional<T> value = Optional.ofNullable((T) _objectMapper.readValue( _objectMapper.treeAsTokens(property.get()), typeFactory.constructType(type))); return value; } catch (final IOException e) { throw new IllegalArgumentException( String.format( "Unable to construct object from configuration; type=%s, property=%s", type, property), e); } }
@Test public void testSegmenter() throws IOException { String[] args = { "-input", "/home/rishi/Desktop/testDoc/To check/paper 2009-Semantic interpretation and knowledge extraction.pdf", "-format", "STDOUT" }; String heading = "Semantic interpretation and knowledge extraction "; Params cliParams = Params.getParams(args); ObjectMapper mapper = new ObjectMapper(); String path = cliParams.getInput(); PdfSections pdf2Xml = new PdfSections(cliParams); pdf2Xml.processFile(path); List<Structure> structure = mapper.readValue(pdf2Xml.generateOutput().get(0), TypeFactory.defaultInstance().constructCollectionType(List.class, Structure.class)); Assert.assertTrue(structure.get(0).getHeading().equals(heading)); }
private Map<String, ContainerQuota> getChangedContainers( final String quotaContainers ) throws java.io.IOException { Map<String, ContainerQuota> changedContainersFiltered = new HashMap<>(); TypeFactory typeFactory = mapper.getTypeFactory(); CollectionType arrayType = typeFactory.constructCollectionType( ArrayList.class, ChangedContainerDto.class ); List<ChangedContainerDto> changedContainers = mapper.readValue( quotaContainers, arrayType ); for ( ChangedContainerDto cont : changedContainers ) { ContainerQuotaDto containerQuotaDto = cont.getQuota(); ContainerSize containerSize = containerQuotaDto.getContainerSize(); ContainerQuota defaultQuota = ContainerSize.getDefaultContainerQuota( containerSize ); if ( containerSize == ContainerSize.CUSTOM ) { defaultQuota = containerQuotaDto.getContainerQuota(); } changedContainersFiltered.put( cont.getHostId(), defaultQuota ); } return changedContainersFiltered; }
/** * Generates a {@link JavaType} that matches the target Thrift field represented by the provided * {@code <E>} enumerated value. If the field's type includes generics, the generics will * be added to the generated {@link JavaType} to support proper conversion. * @param thriftInstance The Thrift-generated class instance that will be converted to/from JSON. * @param field A {@code <E>} enumerated value that represents a field in a Thrift-based entity. * @return The {@link JavaType} representation of the type associated with the field. * @throws NoSuchFieldException if unable to determine the field's type. * @throws SecurityException if unable to determine the field's type. */ protected JavaType generateValueType(final T thriftInstance, final E field) throws NoSuchFieldException, SecurityException { final TypeFactory typeFactory = TypeFactory.defaultInstance(); final Field declaredField = thriftInstance.getClass().getDeclaredField(field.getFieldName()); if(declaredField.getType().equals(declaredField.getGenericType())) { log.debug("Generating JavaType for type '{}'.", declaredField.getType()); return typeFactory.constructType(declaredField.getType()); } else { final ParameterizedType type = (ParameterizedType)declaredField.getGenericType(); final Class<?>[] parameterizedTypes = new Class<?>[type.getActualTypeArguments().length]; for(int i=0; i<type.getActualTypeArguments().length; i++) { parameterizedTypes[i] = (Class<?>)type.getActualTypeArguments()[i]; } log.debug("Generating JavaType for type '{}' with generics '{}'", declaredField.getType(), parameterizedTypes); return typeFactory.constructParametricType(declaredField.getType(), parameterizedTypes); } }
private <T> T parse(JsonNode node, ValueType<T> valueType) throws IOException { JavaType javaType = null; if (valueType instanceof SimpleType) { SimpleType simpleType = (SimpleType) valueType; javaType = TypeFactory.defaultInstance().uncheckedSimpleType(simpleType.getBaseClass()); } else if (valueType instanceof GenericType) { GenericType genericType = (GenericType) valueType; javaType = TypeFactory.defaultInstance().constructParametricType(genericType.getBaseClass(), genericType.getParameterTypes()); } else if (valueType instanceof CollectionType) { CollectionType collectionType = (CollectionType) valueType; javaType = TypeFactory.defaultInstance().constructCollectionType(collectionType.getBaseClass(), collectionType.getElementClass()); } else if (valueType instanceof MapType) { MapType mapType = (MapType) valueType; javaType = TypeFactory.defaultInstance().constructMapType(mapType.getBaseClass(), mapType.getKeyClass(), mapType.getValueClass()); } else { throw new IllegalArgumentException("Unexpected class instance encountered: " + valueType.getClass()); } return (T) parse(node, javaType); }
<T> Map<String, T> loadProps(Class<?> clazz, Function<KvProperty, T> func) { ImmutableMap.Builder<String, T> b = ImmutableMap.builder(); TypeFactory tf = TypeFactory.defaultInstance(); while(clazz != null && !Object.class.equals(clazz)) { for(Field field: clazz.getDeclaredFields()) { KvMapping mapping = field.getAnnotation(KvMapping.class); if(mapping == null) { continue; } JavaType javaType; String typeStr = mapping.type(); if(!typeStr.isEmpty()) { javaType = tf.constructFromCanonical(typeStr); } else { javaType = tf.constructType(field.getGenericType()); } KvProperty property = new KvProperty(this, field.getName(), field, javaType); b.put(property.getKey(), func.apply(property)); } clazz = clazz.getSuperclass(); } return b.build(); }
public WebBookServlet() { File dir = new File("webapi/data"); dir.mkdirs(); try { File file = new File("webapi/data/webbooks.json"); if (file.exists()) { String content = new String(Files.readAllBytes(file.toPath())); JavaType mapType = TypeFactory.defaultInstance() .constructMapType(ConcurrentHashMap.class, String.class, WebBook.class); books = serializeService.deserialize(content, false, mapType, IPermissionService.permitAllNode()); } } catch (IOException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") @Override public Analyzer<?> deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final JsonDeserializer<?> specDeserializer = ctxt .findNonContextualValueDeserializer(TypeFactory.defaultInstance().uncheckedSimpleType(AnalyzerSpec.class)); final AnalyzerSpec spec = (AnalyzerSpec) specDeserializer.deserialize(p, ctxt); final AnalyzerCreationResult creationResult = spec.getAnalyzerType().tryCreateAnalyzer(spec); if (!creationResult.wasSuccessful()) { throw new IOException( "Could not create analyzer from spec, global result: " + creationResult.getGlobalResult() + ", parameter results: "); } return creationResult.getAnalyzer(); }
public static JavaType findJavaType(ClassLoader classLoader, String packageName, Swagger swagger, Property itemProperty, Boolean uniqueItems) { JavaType itemJavaType = ConverterMgr.findJavaType(classLoader, packageName, swagger, itemProperty); @SuppressWarnings("rawtypes") Class<? extends Collection> collectionClass = List.class; if (Boolean.TRUE.equals(uniqueItems)) { collectionClass = Set.class; } return TypeFactory.defaultInstance().constructCollectionType(collectionClass, itemJavaType); }
private static JavaType getOrCreateEnumByNames(ClassLoader classLoader, String packageName, List<String> enums) { String strEnums = enums.toString(); synchronized (LOCK) { JavaType javaType = enumMap.get(strEnums); if (javaType != null) { return javaType; } String enumClsName = packageName + ".Enum" + enumMap.size(); @SuppressWarnings("rawtypes") Class<? extends Enum> enumCls = JavassistUtils.createEnum(classLoader, enumClsName, enums); javaType = TypeFactory.defaultInstance().constructType(enumCls); enumMap.put(strEnums, javaType); return javaType; } }
public static JavaType findJavaType(ClassLoader classLoader, String packageName, Swagger swagger, Property valueProperty) { JavaType valueJavaType = ConverterMgr.findJavaType(classLoader, packageName, swagger, valueProperty); return TypeFactory.defaultInstance().constructMapType(Map.class, TypeFactory.defaultInstance().constructType(String.class), valueJavaType); }
@Override public JavaType doConvert(ClassLoader classLoader, String packageName, Swagger swagger, Object model) { ModelImpl modelImpl = (ModelImpl) model; JavaType javaType = ConverterMgr.findJavaType(modelImpl.getType(), modelImpl.getFormat()); if (javaType != null) { return javaType; } if (modelImpl.getReference() != null) { return ConverterMgr.findByRef(classLoader, packageName, swagger, modelImpl.getReference()); } if (modelImpl.getAdditionalProperties() != null) { return MapPropertyConverter.findJavaType(classLoader, packageName, swagger, modelImpl.getAdditionalProperties()); } if (ObjectProperty.TYPE.equals(modelImpl.getType()) && modelImpl.getProperties() == null && modelImpl.getName() == null) { return TypeFactory.defaultInstance().constructType(Object.class); } // 根据name、property动态生成class if (packageName == null) { throw new Error("packageName should not be null"); } String clsName = packageName + "." + modelImpl.getName(); Class<?> cls = ClassUtils.getOrCreateClass(classLoader, packageName, swagger, modelImpl.getProperties(), clsName); return TypeFactory.defaultInstance().constructType(cls); }
private JavaType getJavaTypeByVendorExtensions(ClassLoader classLoader, Map<String, Object> vendorExtensions) { Class<?> cls = ClassUtils.getClassByVendorExtensions(classLoader, vendorExtensions, SwaggerConst.EXT_JAVA_CLASS); if (cls == null) { return null; } return TypeFactory.defaultInstance().constructType(cls); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = TypeFactory.defaultInstance().constructType(genericParamType); boolean rawJson = ClassUtils.isRawJsonType(parameter); if (genericParamType.getTypeName().equals(String.class.getTypeName()) && rawJson) { return new RawJsonBodyProcessor(targetType); } return new BodyProcessor(targetType); }
@Override public ParamValueProcessor create(Parameter parameter, Type genericParamType) { JavaType targetType = TypeFactory.defaultInstance().constructType(genericParamType); if (isPart(parameter)) { return new PartProcessor(parameter.getName(), targetType); } return new FormProcessor(parameter.getName(), targetType); }
@SuppressWarnings("unchecked") @Test public void testGetValueList() throws Exception { new Expectations() { { request.getHeaders("h1"); result = Collections.enumeration(Arrays.asList("h1v")); } }; HeaderProcessor processor = new HeaderProcessor("h1", TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); Object value = processor.getValue(request); Assert.assertThat((List<String>) value, Matchers.contains("h1v")); }
@SuppressWarnings("unchecked") @Test public void testGetValueSet() throws Exception { new Expectations() { { request.getHeaders("h1"); result = Collections.enumeration(Arrays.asList("h1v")); } }; HeaderProcessor processor = new HeaderProcessor("h1", TypeFactory.defaultInstance().constructCollectionType(Set.class, String.class)); Object value = processor.getValue(request); Assert.assertThat((Set<String>) value, Matchers.contains("h1v")); }
@SuppressWarnings("unchecked") @Test public void testGetValueList() throws Exception { new Expectations() { { request.getParameterValues("name"); result = new String[] {"value"}; } }; ParamValueProcessor processor = new FormProcessor("name", TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); Object value = processor.getValue(request); Assert.assertThat((List<String>) value, Matchers.contains("value")); }
@SuppressWarnings("unchecked") @Test public void testGetValueSet() throws Exception { new Expectations() { { request.getParameterValues("name"); result = new String[] {"value"}; } }; ParamValueProcessor processor = new FormProcessor("name", TypeFactory.defaultInstance().constructCollectionType(Set.class, String.class)); Object value = processor.getValue(request); Assert.assertThat((Set<String>) value, Matchers.contains("value")); }
@Test public void testdecodeResponseNull() throws Exception { JavaType resultType = TypeFactory.unknownType(); Object result = pp.decodeResponse(Buffer.buffer(), resultType); Assert.assertNull(result); ByteArrayInputStream is = new ByteArrayInputStream(new byte[] {}); result = pp.decodeResponse(is, resultType); Assert.assertNull(result); }
@Test public void testField() throws Exception { ClassConfig classConfig = new ClassConfig(); classConfig.setClassName("cse.ut.testField"); FieldConfig fieldConfig = classConfig.addField("intField", int.class); fieldConfig.setGenGetter(true); fieldConfig.setGenSetter(true); fieldConfig = classConfig.addField("intArrayField", int[].class); fieldConfig.setGenGetter(true); fieldConfig.setGenSetter(true); fieldConfig = classConfig.addField("listStringField", TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); fieldConfig.setGenGetter(true); fieldConfig.setGenSetter(true); Class<?> cls = JavassistUtils.createClass(classConfig); Field field = cls.getField("intField"); Assert.assertEquals(Integer.class, field.getType()); Method method = cls.getMethod("getIntField"); Assert.assertEquals(Integer.class, method.getReturnType()); field = cls.getField("intArrayField"); Assert.assertEquals(int[].class, field.getType()); method = cls.getMethod("getIntArrayField"); Assert.assertEquals(int[].class, method.getReturnType()); field = cls.getField("listStringField"); Assert.assertEquals("java.util.List<java.lang.String>", field.getGenericType().getTypeName()); method = cls.getMethod("getListStringField"); Assert.assertEquals("java.util.List<java.lang.String>", method.getGenericReturnType().getTypeName()); }
@Test public void testAddParameter() { ClassConfig classConfig = new ClassConfig(); classConfig.setIntf(true); String intfName = "cse.ut.TestAddParameter"; classConfig.setClassName(intfName); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("method"); methodConfig.setResult(TypeFactory.defaultInstance().constructCollectionType(List.class, String.class)); methodConfig.addParameter("map", TypeFactory.defaultInstance().constructMapType(Map.class, String.class, String.class)); methodConfig.addParameter("set", TypeFactory.defaultInstance().constructCollectionType(Set.class, String.class)); classConfig.addMethod(methodConfig); Class<?> intf = JavassistUtils.createClass(classConfig); Assert.assertEquals(intfName, intf.getName()); Method method = ReflectUtils.findMethod(intf, "method"); Assert.assertEquals("method", method.getName()); Assert.assertEquals("java.util.List<java.lang.String>", method.getGenericReturnType().getTypeName()); Type[] types = method.getGenericParameterTypes(); Assert.assertEquals("java.util.Map<java.lang.String, java.lang.String>", types[0].getTypeName()); Assert.assertEquals("java.util.Set<java.lang.String>", types[1].getTypeName()); }
@Test public void singleWrapperInt() throws Exception { ClassConfig classConfig = new ClassConfig(); classConfig.setClassName("cse.ut.single.IntWrapper"); classConfig.addField("intField", TypeFactory.defaultInstance().constructType(int.class)); JavassistUtils.genSingleWrapperInterface(classConfig); Class<?> wrapperClass = JavassistUtils.createClass(classConfig); SingleWrapper instance = (SingleWrapper) wrapperClass.newInstance(); instance.writeField(100); int intFieldValue = (int) instance.readField(); Assert.assertEquals(100, intFieldValue); }
@Test public void testGetNameForGenerateCode() { JavaType jt = TypeFactory.defaultInstance().constructType(byte[].class); String name = JavassistUtils.getNameForGenerateCode(jt); Assert.assertEquals("byte[]", name); jt = TypeFactory.defaultInstance().constructType(Byte[].class); name = JavassistUtils.getNameForGenerateCode(jt); Assert.assertEquals("java.lang.Byte[]", name); jt = TypeFactory.defaultInstance().constructType(Object[].class); name = JavassistUtils.getNameForGenerateCode(jt); Assert.assertEquals("java.lang.Object[]", name); }
public static WrapSchema getOrCreateSchema(Type type) { JavaType javaType = TypeFactory.defaultInstance().constructType(type); // List<String> -> java.util.List<java.lang.String> // List<List<String>> -> java.util.List<java.util.List<java.lang.String>> String key = javaType.toCanonical(); return getOrCreateSchema(key, () -> { if (!isNeedWrap(javaType.getRawClass())) { // 可以直接使用 Schema<?> schema = RuntimeSchema.createFrom(javaType.getRawClass()); return WrapSchemaFactory.createSchema(schema, WrapType.NOT_WRAP); } // 需要包装 WrapClassConfig config = new WrapClassConfig(); config.setType(WrapType.NORMAL_WRAP); config.setClassName("gen.wrap.protobuf." + key.replaceAll("[<>]", "_").replace("[", "array_")); if (!Void.TYPE.isAssignableFrom(javaType.getRawClass())) { config.addField("field0", javaType); } JavassistUtils.genSingleWrapperInterface(config); return createWrapSchema(config); }); }
@Override public void init(ProtobufSchema schema, Type... types) { writer = ProtobufManager.getMapper().writer(schema); reader = ProtobufManager.getMapper().reader(schema); // 需要考虑void场景 if (types.length == 1) { JavaType javaType = TypeFactory.defaultInstance().constructType(types[0]); writer = writer.forType(javaType); reader = reader.forType(javaType); } }
@Override public void init(ProtobufSchema schema, Type... types) { writer = ProtobufManager.getMapper().writer(schema); reader = ProtobufManager.getMapper().reader(schema); // 需要考虑没参数的场景 if (types.length == 1) { JavaType javaType = TypeFactory.defaultInstance().constructType(types[0]); writer = new StandardObjectWriter(writer.forType(javaType)); reader = new StandardObjectReader(reader.forType(javaType)); } }