Skip to content

Commit

Permalink
Don't use reflection when possible
Browse files Browse the repository at this point in the history
Signed-off-by: Lukáš Petrovický <lukas@petrovicky.net>
  • Loading branch information
triceo committed Apr 25, 2020
1 parent 9cf3b42 commit a0ec735
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/java/org/eclipse/yasson/internal/model/ClassModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import jakarta.json.bind.config.PropertyNamingStrategy;
Expand All @@ -37,7 +38,9 @@ public class ClassModel {

private final ClassModel parentClassModel;

private final Constructor<?> defaultConstructor;
private final AtomicBoolean isInitialized = new AtomicBoolean(false);

private Constructor<?> defaultConstructor;

/**
* A map of all class properties, including properties from superclasses. Used to access by name.
Expand Down Expand Up @@ -77,7 +80,6 @@ public ClassModel(Class<?> clazz,
this.classCustomization = customization;
this.parentClassModel = parentClassModel;
this.propertyNamingStrategy = propertyNamingStrategy;
this.defaultConstructor = ReflectionUtils.getDefaultConstructor(clazz, false);
setProperties(new ArrayList<>());
}

Expand Down Expand Up @@ -183,6 +185,13 @@ public Map<String, PropertyModel> getProperties() {
* @return default constructor
*/
public Constructor<?> getDefaultConstructor() {
// Lazy-loads the default constructor to avoid Java 9+ "Illegal reflective access" warnings where possible.
// Example: Deserialization into Map won't use this constructor, and therefore never needs to call this method.
// Note: Null is a valid result and needs to be cached.
if (!isInitialized.get()) {
defaultConstructor = ReflectionUtils.getDefaultConstructor(clazz, false);
isInitialized.set(true);
}
return defaultConstructor;
}
}

0 comments on commit a0ec735

Please sign in to comment.