All Downloads are FREE. Search and download functionalities are using the official Maven repository.

au.csiro.sparkle.cmd.DefaultObjectFactory Maven / Gradle / Ivy

The newest version!
package au.csiro.sparkle.cmd;

import java.util.HashMap;
import java.util.Map;

import au.csiro.sparkle.common.ObjectFactory;
import au.csiro.sparkle.common.ObjectProvider;

public class DefaultObjectFactory implements ObjectFactory{

	static class ClassProvider extends ObjectProvider{
		private final Class clazz;

		public ClassProvider(Class clazz) {
	        this.clazz = clazz;
        }
		@SuppressWarnings("unchecked")
        public ClassProvider(String className) {
	        try {
	            this.clazz = (Class) Class.forName(className);
            } catch (ClassNotFoundException ex) {
            	throw new RuntimeException(ex);
            }
        }

		@Override
        public T provide() {
			try {
	           return  clazz.newInstance();
            } catch (InstantiationException ex) {
            	throw new RuntimeException(ex);
            } catch (IllegalAccessException ex) {
            	throw new RuntimeException(ex);
            }
        }
	}	
	protected Map> modules  = new HashMap<>();
	
	public void registerClass(String name, Class clazz) {
		register(name, new ClassProvider(clazz));
	}
	public  void register(String name, ObjectProvider provider) {
		modules.put(name, provider);
	}
	@Override
    public T create(String clazzName) {
		return modules.computeIfAbsent(clazzName, name->  new ClassProvider(name)).provide();
    }
	
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy