Object instance = cls.newInstance();
if (expectedInstance != null && !expectedInstance.isInstance(instance))
{
// Given type '{name}' is not of expected type '{expectedName}'.
MessageException ex = new MessageException();
ex.setMessage(UNEXPECTED_TYPE, new Object[] {instance.getClass().getName(), expectedInstance.getName()});
ex.setCode(MessageException.CODE_SERVER_RESOURCE_UNAVAILABLE);
throw ex;
}
return instance;
}
catch (IllegalAccessException ia)
{
boolean details = false;
StringBuffer message = new StringBuffer("Unable to create a new instance of type ");
message.append(type);
//Look for a possible cause...
// Class might not have a suitable constructor?
if (!hasValidDefaultConstructor(cls))
{
details = true;
}
// Unable to create a new instance of type '{type}'.
MessageException ex = new MessageException();
ex.setMessage(CANNOT_CREATE_TYPE, new Object[] {type});
if (details)
{
//Types must have a public, no arguments constructor
ex.setDetails(CANNOT_CREATE_TYPE, "0");
}
ex.setCode(MessageException.CODE_SERVER_RESOURCE_UNAVAILABLE);
throw ex;
}
catch (InstantiationException ine)
{
String variant = null;
//Look for a possible cause...
if (cls != null)
{
// Class is really an interface?
if (cls.isInterface())
{
// Interfaces cannot be instantiated.
variant = "1";
}
else if (isAbstract(cls))
{
//Abstract types cannot be instantiated.
variant = "2";
}
// Class might not have a suitable constructor?
else if (!hasValidDefaultConstructor(cls))
{
// Types cannot be instantiated without a public, no arguments constructor.
variant = "3";
}
}
MessageException ex = new MessageException();
ex.setMessage(CANNOT_CREATE_TYPE, new Object[] {type});
if (variant != null)
ex.setDetails(CANNOT_CREATE_TYPE, variant);
ex.setCode(MessageException.CODE_SERVER_RESOURCE_UNAVAILABLE);
throw ex;
}
catch (SecurityException se)
{
MessageException ex = new MessageException();
ex.setMessage(SECURITY_ERROR, new Object[] {type});
ex.setCode(MessageException.CODE_SERVER_RESOURCE_UNAVAILABLE);
ex.setRootCause(se);
throw ex;
}
catch (Exception e)
{
MessageException ex = new MessageException();
ex.setMessage(UNKNOWN_ERROR, new Object[] {type});
ex.setCode(MessageException.CODE_SERVER_RESOURCE_UNAVAILABLE);
ex.setRootCause(e);
throw ex;
}
}