dimanche 18 février 2018

Java cast based on the value of a field

Is it possible to do a dynamic cast based on the value of some object field? For example. I have a class User that has a field userType which is of type UserType with possible values CLIENT and DRIVER. I have classes Client and Driver that extend from User. I would like to do a dynamic cast based on this field. I'd like something like this.

User user = userService.getById(id);

// returns Client if userType.equals(UserType.CLIENT)
// returns Driver if userType.equals(UserType.DRIVER)
return user.dynamicCast(user.getUserType()); 

Basically, I'd need something like Jackson's subtype, but I just need to invoke it manually from my code. This is how Jackson works:

@JsonTypeInfo(
        use = JsonTypeInfo.Id.NAME, 
        include = JsonTypeInfo.As.PROPERTY, 
        property = "userType", 
        visible = true, 
        defaultImpl = InvalidUser.class)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Client.class, name = "CLIENT"),
    @JsonSubTypes.Type(value = Driver.class, name = "DRIVER")
})
public abstract class User { /* ... */ }

Is something like that possible to dynamically invoke from code? I want something like that to avoid the instanceof checks.





Aucun commentaire:

Enregistrer un commentaire