[JAVA-2688] BsonCreator annotation processing depends on arbitrary ordering of constructors and factory methods Created: 04/Dec/17  Updated: 28/Oct/23  Resolved: 04/Dec/17

Status: Closed
Project: Java Driver
Component/s: POJO
Affects Version/s: None
Fix Version/s: 3.6.0

Type: Improvement Priority: Major - P3
Reporter: Jeffrey Yemin Assignee: Ross Lawley
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

The org.bson.codecs.pojo.ConventionAnnotationImpl#processPropertyAnnotations method first looks for constructors annotated with @BsonCreator then for static methods annotated with BsonCreator. But if a class contains more than one of either type, the results are unpredictable and depend on the order that the constructors or methods in the lists provided by the reflection API.

For example, a class like:

public class Person {
    // oops, missing BsonProperty annotation
    @BsonCreator Person(String name);
 
    // properly annotated
    @BsonCreator Person(@BsonProperty("name") String name, @BsonProperty("age") int age);
    // ...
}

will result in an exception if the first constructor is first in the list, but not if the second constructor is first in the list.

If the intention is that at most one constructor or static method annotated with @BsonCreator is permitted, then all of them should be examined rather than breaking out of the loop on the first one.



 Comments   
Comment by Githook User [ 04/Dec/17 ]

Author:

{'username': 'rozza', 'email': 'ross.lawley@gmail.com', 'name': 'Ross Lawley'}

Message: ConventionAnnotation updates

Ensure all constuctors are validated.
Ignore synthetic and bridge methods when checking for @BsonCreator
methods / constructors.

JAVA-2688
Branch: 3.6.x
https://github.com/mongodb/mongo-java-driver/commit/19ad9bf8707233edb56059c0772e2d38f0d22fed

Comment by Githook User [ 04/Dec/17 ]

Author:

{'username': 'rozza', 'email': 'ross.lawley@gmail.com', 'name': 'Ross Lawley'}

Message: ConventionAnnotation updates

Ensure all constuctors are validated.
Ignore synthetic and bridge methods when checking for @BsonCreator
methods / constructors.

JAVA-2688
Branch: master
https://github.com/mongodb/mongo-java-driver/commit/19ad9bf8707233edb56059c0772e2d38f0d22fed

Comment by Jeffrey Yemin [ 04/Dec/17 ]

Note: I noticed this while debugging use of the PojoCodec with Kotlin data class. A Kotlin data class is transformed to Java such that two constructors are produced that are annotated with @BsonCreator, one of which is synthetic and contains a few extra parameters that are of course not annotated. Strangely, multiple runs of the same code, without recompilation, generated different order of those constructors in the list, so sometimes it would work fine and other times it would throw an exception.

Generated at Thu Feb 08 08:57:50 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.