Class templates in Java

Nov 10, 2007 14:39

Following is a suggested workqround for creating Java class templates. EnumKey class is a template for creating enumeration Keys with different structure.


Example of usage would be the following:

public static class PRK extends EnumKey
{
static
{
EnumKey.register(PRK.class,
new Class[] {
BaseEntity.class,
ScreenType.class,
ScreenPlacementType.class
},
new Object[][] {
new BaseEntity[] {PARENT_YES, PARENT_NO},
DomainManager.getDomainArray(ScreenType.class),
DomainManager.getDomainArray(ScreenPlacementType.class)
}
);
}
}

public static class RRK extends EnumKey
{
static
{
EnumKey.register(RRK.class,
new Class[] {
ScreenType.class
},
new Object[][] {
DomainManager.getDomainArray(ScreenType.class),
}
);
}
}

public class EnumKey extends CompositeKey
{
public static Object ANY = new Integer(Integer.MAX_VALUE);

private static Hashtable hKeyClasses = new Hashtable();
private static Hashtable hEnumerations = new Hashtable();

public static void register(Class aClazz, Class[] keyClasses, Object[][] enumerations)
{
if (!CompositeKey.class.isAssignableFrom(aClazz))
throw new IllegalArgumentException("Parameter class has to be a subclass of EnumKey");

if (keyClasses == null || keyClasses.length == 0)
throw new IllegalArgumentException("Key structure missing");

if (enumerations == null || enumerations.length == 0 || enumerations.length != keyClasses.length)
throw new IllegalArgumentException("Key enumeration structure missing or invalid (does not match the key structure)");

hKeyClasses.put(aClazz, keyClasses);
hEnumerations.put(aClazz, enumerations);
}

public EnumKey()
{

}

public EnumKey(Object... elements)
{
setEnumKeyValues(elements);
}

public void setEnumKeyValues(Object... elements)
{
Class[] keyClasses = getKeyClasses();
Object[][] enumerations = getEnumerations();

if (keyClasses == null || enumerations == null)
throw new IllegalArgumentException("Class not registered");

if (elements.length != keyClasses.length)
throw new IllegalArgumentException("Invalid number of keys");

for (int i = 0; i < elements.length; i++)
{
if (elements[i] == null)
throw new IllegalArgumentException("Key may not be null");

if (!elements[i].getClass().equals(keyClasses[i]) && elements[i] != ANY)
throw new IllegalArgumentException("Invalid key class " + elements[i].getClass().getName() + ". Expected: " + keyClasses[i].getName());

boolean foundMatch = false;
if (elements[i] != ANY)
{
for (int j = 0; j < enumerations[i].length; j++)
{
Object enumElement = enumerations[i][j];
if (enumElement.equals(elements[i]))
{
foundMatch = true;
break;
}
}
if (!foundMatch)
throw new IllegalArgumentException("Key value does not exist in the enumeration" + elements[i]);
}
}

super.setKeyValues(elements);
}

public Class[] getKeyClasses()
{
return hKeyClasses.get(getClass());
}

public Object[][] getEnumerations()
{
return hEnumerations.get(getClass());
}

}
Previous post Next post
Up