Есть ли более эффективный способ достижения этого результата.По сути, я хочу сначала посмотреть на Section
с самым длинным значением getContextPath()
.
enum Section {
Provider("Provider", "com.app.provider"),
Container("Container", "com.app");
/**
* The key for this Section.
*/
private String key;
/**
* The context path for this Section.
*/
private String contextPath;
/**
* Create a new Section.
*
* @param key The Key for this section.
* @param contextPath The Context Path for this section.
*/
Section(String key, String contextPath) {
this.key = key;
this.contextPath = contextPath;
}
/**
* Retrieve the String representation of this Section.
*
* @return The String value.
*/
@SuppressWarnings("NullableProblems")
@Override
public String toString() {
return this.key;
}
/**
* Retrieve the Context Path for this Section.
*
* @return The Context Path.
*/
public String getContextPath()
{
return this.contextPath;
}
}
// Keep in mind that these may be dynamically loaded, and won't always be
// statically loaded like this.
private static final Map<Section, String> sectionLoggerIds = new HashMap<>() {{
put(Section.Container, "some.id");
put(Section.Provider, "some.other.id");
}};
/**
* Retrieve a Logger based on a Context.
*
* @param context The Context.
* @return The Logger
*/
public static Logger logger(Context context) {
// Create a TreeSet for sorting the values, and set it up
// to sort them longest first.
Set<Section> sectionSet = new TreeSet<>(new Comparator<Section>() {
@Override
public int compare(Section section1, Section section2) {
return Integer.compare(
section2.getContextPath().length(),
section1.getContextPath().length()
);
}
});
// Add all of the relevant Section objects.
sectionSet.addAll(sectionLoggerIds.keySet());
// Search the Sections, starting with the longest
// contextPath first.
for(Section section : sectionSet) {
if (context.getClass().getName().contains(section.getContextPath())) {
return getLogger(sectionLoggerIds.get(section));
}
}
return null;
}