de.tsl2.nano.plugin.Plugins Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of tsl2.nano.common Show documentation
Show all versions of tsl2.nano.common Show documentation
TSL2 Framework Commons (Collections, Actions/Excecution, Readers, Xml, Print, Mail, FuzzyFinder, Proxies, Network-Structure)
/*
* File: $HeadURL$
* Id : $Id$
*
* created by: Tom
* created on: 09.03.2018
*
* Copyright: (c) Thomas Schneider 2018, all rights reserved
*/
package de.tsl2.nano.plugin;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import de.tsl2.nano.core.cls.BeanClass;
import de.tsl2.nano.core.cls.ClassFinder;
import de.tsl2.nano.core.log.LogFactory;
import de.tsl2.nano.core.util.StringUtil;
/**
* Is able to find all implementations of an interface and delegates each call to all loaded implementations to do an
* inspections or decoration.
*
* @author Tom
* @version $Revision$
*/
public class Plugins {
static final Log LOG = LogFactory.getLog(Plugins.class);
private static Plugins self = null;
Map, Object> implementations = new HashMap<>();
public static T process(Class pluginInterface) {
return process(pluginInterface, DecorationProxy.class);
}
@SuppressWarnings("unchecked")
public static T process(Class pluginInterface, Class extends InvocationHandler> processingType) {
if (self == null)
self = new Plugins();
Object dec = self.implementations.get(pluginInterface);
if (dec == null) {
dec = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
new Class[] { pluginInterface }, BeanClass.createInstance(processingType, pluginInterface));
self.implementations.put(pluginInterface, dec);
}
return (T) dec;
}
/**
* instances of provided implementations for the given interface
*/
public static List getImplementations(Class interfaze) {
Collection> implClasses = ClassFinder.self().findClass(interfaze);
ArrayList handler = new ArrayList<>(implClasses.size());
LOG.info("implementations for " + interfaze + "\n" + StringUtil.toFormattedString(implClasses, -1));
for (Class implClass : implClasses) {
handler.add(BeanClass.createInstance(implClass));
}
return handler;
}
static final void log(Object txt) {
System.out.println(txt);
}
}