view src/samer/core_/Registry.java @ 8:5e3cbbf173aa tip

Reorganise some more
author samer
date Fri, 05 Apr 2019 22:41:58 +0100
parents bf79fb79ee13
children
line wrap: on
line source
package samer.core;
import  java.util.Hashtable;

/**
	The Registry stores Object class - Viewer class pairs.
	Associations can be added as Class objects or Class names (Strings).
	When creating a Viewer for a given object, matching is done on the
	basis that an exact Class matches is preferred, but failing that, parent
	Class matches are attempted up the Class heirarchy until a match is
	found.
*/

public class Registry
{
	static { Shell.trace("initialising Registry"); }
	private static Hashtable map=new Hashtable();

	/** register viewer as a Viewer class for objects of class obj */
	public static void put(Class obj, Class viewer) { map.put(obj.getName(),viewer); }

	/** Registering by class name saves loading the class itself
		until it is actually needed. */
	public static void put(String obj, String viewer) { map.put(obj,viewer); }

	/** Create and return a Viewer for the supplied object */
	public static Viewer createViewer(Object obj)
	{
		Class cl=obj.getClass();

		// lookup by class NAME
		Object vwr=map.get(cl.getName());
		while (vwr==null) {
			cl=cl.getSuperclass();
			if (cl==null) return null;
			vwr=map.get(cl.getName());
		}

		Class [] types = { cl };
		Object [] parms = { obj };

		try {
			if (vwr instanceof String) vwr=Class.forName((String)vwr);
			return (Viewer)((Class)vwr).getConstructor(types).newInstance(parms);
		} catch (Exception ex) {
			Shell.trace(ex.toString());
			return null;
		}
	}
}