import javassist.LoaderClassPath;
import javassist.NotFoundException;
import javax.annotation.concurrent.GuardedBy;
+import javax.annotation.concurrent.ThreadSafe;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* Users of this utility class are expected to synchronize on this instance
* it they need to ensure atomic operations on it.
*/
+@NonNullByDefault
+@ThreadSafe
public final class JavassistUtils {
private static final Logger LOG = LoggerFactory.getLogger(JavassistUtils.class);
private static final Map<ClassPool, JavassistUtils> INSTANCES = new WeakHashMap<>();
+ @GuardedBy("this")
private final Map<ClassLoader, ClassPath> loaderClassPaths = new WeakHashMap<>();
+ @GuardedBy("this")
private final ClassPool classPool;
private JavassistUtils(final ClassPool pool) {
* @return shared utility instance for specified pool
*/
public static synchronized JavassistUtils forClassPool(final ClassPool pool) {
- JavassistUtils ret = INSTANCES.get(requireNonNull(pool));
- if (ret == null) {
- ret = new JavassistUtils(pool);
- INSTANCES.put(pool, ret);
- }
- return ret;
+ return INSTANCES.computeIfAbsent(requireNonNull(pool), JavassistUtils::new);
}
/**
* @throws NotFoundException when the prototype class is not found
*/
@Beta
+ @SuppressWarnings("checkstyle:illegalCatch")
public synchronized CtClass instantiatePrototype(final String prototype, final String fqn,
final ClassCustomizer customizer) throws CannotCompileException, NotFoundException {
final CtClass result = classPool.getAndRename(prototype, fqn);
}
@GuardedBy("this")
- public CtClass asCtClass(final Class<?> class1) {
- return get(this.classPool, class1);
- }
-
- public CtClass get(final ClassPool pool, final Class<? extends Object> cls) {
+ public CtClass asCtClass(final Class<?> cls) {
try {
- return pool.get(cls.getName());
+ return classPool.get(cls.getName());
} catch (NotFoundException nfe1) {
appendClassLoaderIfMissing(cls.getClassLoader());
try {
- return pool.get(cls.getName());
+ return classPool.get(cls.getName());
} catch (final NotFoundException nfe2) {
LOG.warn("Appending ClassClassPath for {}", cls, nfe2);
- pool.appendClassPath(new ClassClassPath(cls));
+ classPool.appendClassPath(new ClassClassPath(cls));
try {
- return pool.get(cls.getName());
+ return classPool.get(cls.getName());
} catch (NotFoundException e) {
- LOG.warn("Failed to load class {} from pool {}", cls, pool, e);
+ LOG.warn("Failed to load class {} from pool {}", cls, classPool, e);
throw new IllegalStateException("Failed to load class", e);
}
}