org.databene.commons.bean.ClassCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of databene-commons Show documentation
Show all versions of databene-commons Show documentation
'databene commons' is an open source Java library by Volker Bergmann.
It provides extensions to the Java core library by utility classes, abstract concepts
and concrete implementations.
/*
* Copyright (C) 2004-2014 Volker Bergmann ([email protected]).
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.databene.commons.bean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.databene.commons.BeanUtil;
import org.databene.commons.ConfigurationError;
import org.databene.commons.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides classes by name, supporting package import and local class names.
*
* Created at 15.11.2008 17:03:04
* @since 0.4.6
* @author Volker Bergmann
*/
public class ClassCache {
private static final Logger LOGGER = LoggerFactory.getLogger(ClassCache.class);
private Map> classes;
private List packages;
private Set nonClassNames = new HashSet(1000);
public ClassCache() {
classes = new HashMap>();
packages = new ArrayList();
importPackage("java.lang");
}
public void importClass(String className) {
className = className.trim();
if (className.endsWith(".*"))
importPackage(className.substring(0, className.length() - 2));
else
classes.put(StringUtil.lastToken(className, '.'), BeanUtil.forName(className));
}
public void importPackage(String packageName) {
packages.add(packageName);
}
public Class> forName(String name) {
Class> result = classes.get(name);
if (result != null)
return result;
if (!nonClassNames.contains(name)) {
try {
result = BeanUtil.forName(name);
classes.put(result.getSimpleName(), result);
return result;
} catch (ConfigurationError e) {
nonClassNames.add(name);
LOGGER.debug("class not found: {}", name);
}
}
for (String pkg : packages) {
String fqnTrial = pkg + '.' + name;
if (!nonClassNames.contains(fqnTrial)) {
try {
result = BeanUtil.forName(fqnTrial);
classes.put(result.getSimpleName(), result);
return result;
} catch (ConfigurationError e) {
nonClassNames.add(fqnTrial);
LOGGER.debug("class not found: {}", name);
}
}
}
throw new ConfigurationError("Class not found: " + name);
}
}