Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom Enum Codec is not called in most situations #2264

Closed
eheimburg opened this issue Feb 20, 2023 · 2 comments
Closed

Custom Enum Codec is not called in most situations #2264

eheimburg opened this issue Feb 20, 2023 · 2 comments
Labels
Milestone

Comments

@eheimburg
Copy link
Contributor

eheimburg commented Feb 20, 2023

Describe the bug
It's not possible to use a custom Codec for an enum. The problem is that the built-in converters are checked first. There's a line in Conversions.java where it converts an enum to a string, bypassing the codecs.

To Reproduce
I've created a reproducer here: https://github.com/eheimburg/enumserializedbug

It includes a custom codec factory and a custom codec for an enum. The factory prints when it's called, so it's easy to see that the factory isn't called for the needed codec.

Please complete the following information:

  • Server Version:
  • Driver Version:
  • Morphia Version: 2.3.0

Additional Info
I was able to work around this issue by creating a custom Converter for my enum. So this is not blocking me, but it does seem weird and surprising.


My goal in creating the custom enum codec is to handle invalid values better (defaulting to e.g. INVALID instead of throwing an exception). If the stock converter is important for performance reasons, I'd be happy with any solution that lets me handle invalid enum values.

@eheimburg eheimburg added the bug label Feb 20, 2023
@eheimburg eheimburg changed the title Custom Enum Codec is not used in most situations Custom Enum Codec is not called in most situations Feb 20, 2023
@eheimburg
Copy link
Contributor Author

Oh, and for quick access: I believe the culprit is in dev.morphia.mapping.codec.Conversions in convert() at line 150:

            if (target.equals(String.class)) {
                return (T) value.toString();
            }
            if (target.isEnum() && fromType.equals(String.class)) {
                return (T) Enum.valueOf((Class<? extends Enum>) target, (String) value);
            }

Since all enums are converted as primitives, there's never an attempt to find a codec.

(This means the built-in EnumCodec is largely unused also, from what I can tell.)

@evanchooly
Copy link
Member

enums have long been a problem because it seems the driver's codec usually gets in the way. I thought I had this fixed way back but it seems there's a bit more work to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants