Skip to content

Commit

Permalink
GH-212: Optimise SubclassClassifier.classify()
Browse files Browse the repository at this point in the history
Fixes #212

The `classifiable` class checked twice: by itself
and then as a first iteration for the next loop for subclasses.

* Fix `SubclassClassifier.classify()` to start subclasses loop
from the `exceptionClass.getSuperclass()`
  • Loading branch information
artembilan committed Dec 14, 2023
1 parent 561d41a commit 8b87e8a
Showing 1 changed file with 9 additions and 8 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright 2006-2022 the original author or authors.
* Copyright 2006-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,24 +24,24 @@
* A {@link Classifier} for a parameterised object type based on a map. Classifies objects
* according to their inheritance relation with the supplied type map. If the object to be
* classified is one of the keys of the provided map, or is a subclass of one of the keys,
* then the map entry value for that key is returned. Otherwise returns the default value
* then the map entry value for that key is returned. Otherwise, returns the default value
* which is null by default.
*
* @author Dave Syer
* @author Gary Russell
* @author Artem Bilan
* @param <T> the type of the thing to classify
* @param <C> the output of the classifier
*/
@SuppressWarnings("serial")
public class SubclassClassifier<T, C> implements Classifier<T, C> {

private ConcurrentMap<Class<? extends T>, C> classified = new ConcurrentHashMap<>();
private ConcurrentMap<Class<? extends T>, C> classified;

private C defaultValue = null;
private C defaultValue;

/**
* Create a {@link SubclassClassifier} with null default value.
*
*/
public SubclassClassifier() {
this(null);
Expand Down Expand Up @@ -86,7 +86,7 @@ public void setTypeMap(Map<Class<? extends T>, C> map) {
}

/**
* The keys is the type and this will be mapped along with all subclasses to the
* The key is the type and this will be mapped along with all subclasses to the
* corresponding value. The most specific types will match first.
* @param type the type of the input object
* @param target the target value for all such types
Expand All @@ -103,7 +103,6 @@ public void add(Class<? extends T> type, C target) {
*/
@Override
public C classify(T classifiable) {

if (classifiable == null) {
return this.defaultValue;
}
Expand All @@ -116,7 +115,9 @@ public C classify(T classifiable) {

// check for subclasses
C value = null;
for (Class<?> cls = exceptionClass; !cls.equals(Object.class) && value == null; cls = cls.getSuperclass()) {
for (Class<?> cls = exceptionClass.getSuperclass(); !cls.equals(Object.class)
&& value == null; cls = cls.getSuperclass()) {

value = this.classified.get(cls);
}

Expand Down

0 comments on commit 8b87e8a

Please sign in to comment.