I've declare the following JsType in order to manipulate [GeoJson][1] compliant data :
@JsType
public class FeatureCollection extends GeoJson {
@JsProperty
private Feature[] features;
public FeatureCollection() {
super("FeatureCollection");
features = new Feature[]{};
}
public Feature[] getFeatures() {
return features;
}
Sometimes I need to pass my FeatureCollection
object to external libraries (like Turfs.js for instance to perform unit conversion) which access data throught features
properties. The lib returns me a new object with same properties (they follow the GeoJson RFC like my JsType) but I can't cast it back to FeatureCollection
:
FeatureCollection fc = new FeatureCollection();
Object o = TurfUtils.toWgs84(fc); // Works and give an object which respect the FeatureCollection scheme (ie an array of Features) when I print it on the javascript console.
FeatureCollection featureCollection = TurfUtils.toWgs84(fc); // Throw a java.lang.ClassCastException
The Turf library is JsInteroped:
@JsType(isNative = true, namespace = GLOBAL, name = "turf")
public class TurfUtils {
public static native <T extends GeoJson> T toWgs84(T geojson);
}
When making my FeatureCollection a native JsType, it works but prevent me to use my current constructor, so I'm looking for a way to cast back a javascript object to my JsType. [1]: https://www.rfc-editor.org/rfc/rfc7946
As Colin explained, you don't have any type to check in a
GeoJson
object, so you can not useinstanceof
or other OOP techniques to cast it back to the specific type safety. You must set the type asnative=true, name="Object", namespace=GLOBAL
and then you can useJs.cast
to cast it back as aGeoJson
type.If you want something more OOP, you can use a visitor pattern and hide the "manual type checking" behind this visitor, for example:
Example based on this one which also includes jackson annotation so it can be in the server side too.