184.5.2. polymorphic 개체 매핑이란 무엇입니까?
일부 경우에는 직렬화된 오브젝트의 수신자가 오브젝트 유형을 미리 알 수 없습니다. 예를 들어, 이 개체 배열은 다형성 개체 배열의 경우에 적용됩니다.For example, this applies to the case of a polymorphic object array. abstract type, Shape
, and its subtypes, Triangle
, square
등을 고려하십시오.
package com.example; ... public abstract class Shape { } public class Triangle extends Shape { ... } public class Square extends Shape { ... } public class ListOfShape { public List<Shape> shapes; ... }
다음과 같이 셰이프(ListOfShape)의 배열 목록을 인스턴스화하고 serialize할 수 있습니다.You can instantiate and serialize an array list of shapes (ListOfShape
) as follows:
ObjectMapper objectMapper = new ObjectMapper(); ListOfShape shapeList = new ListOfShape(); shapeList.shapes = new ArrayList<Shape>(); shapeList.shapes.add(new Triangle()); shapeList.shapes.add(new Square()); String serialized = objectMapper.writeValueAsString(shapeList);
그러나 이제 수신자 측면에서 문제가 있습니다. 이 유형을 readValue()
에 대한 두 번째 인수로 지정하여 수신자에 ListOfShape
오브젝트를 예상하도록 지시할 수 있습니다.
MyClass myobject = objectMapper.readValue(serialized, ListOfShape.class); ObjectMapper objectMapper = new ObjectMapper();
그러나 목록의 첫 번째 요소가 Triangle
이고 두 번째 요소는 squa re
임을 알 수 있는 방법은 없습니다. 이 문제를 해결하려면 다음 섹션에서 설명하는 대로 다형성 개체 매핑 을 활성화해야 합니다.