Tuesday, November 15, 2011

Instantiating Class via Reflection

These are snippets from an old object I use from time to time, the "InstanceTypeis a generic type of the enclosing class, you may replace it with Object or '?' respectively. 


First we find the desired constructor:


/**
* Searches for the constructor with the specified parameters in the supplied class object.

* @param _class The class which contains the constructor with the specified parameters.
* @param parameterTypes The constructor parameters types.
* @return The constructor instance of the supplied class.
* @throws ConstructorNotFoundException if a constructor with the supplied specifications was not found.
*/
@SuppressWarnings("unchecked")
private Constructor<InstanceType> findAConstructor(Class<InstanceType> _class, Class<?>[] parameterTypes)
throws ConstructorNotFoundException {
Constructor<?>[] constructors = _class.getConstructors();
for (Constructor<?> constructor2 : constructors)
if (compareConstructorParametersTypes(parameterTypes, constructor2.getParameterTypes()))
return (Constructor<InstanceType>) constructor2;
throw new ConstructorNotFoundException("There was no match for Constructor: \n  " + _class.getSimpleName() + "("
+ ReflectiveTools.parseParametersType(parameterTypes) + "); \n  In the specified class object: " + _class.getName());
}


Later just to invoke it to get the object:


public final InstanceType newInstance(Object... parameters)
throws ClassInstantiationException {
try {
checkParameters(parameters);
return constructor.newInstance(parameters);
} catch (IllegalArgumentException e) {
throw new ClassInstantiationException(this, parameters, e);
} catch (IllegalAccessException e) {
throw new ClassInstantiationException(this, parameters, e);
} catch (InvocationTargetException e) {
throw new ClassInstantiationException(this, parameters, e);
} catch (InstantiationException e) {
throw new ClassInstantiationException(this, parameters, e);
} catch (WrongParameterType e) {
throw new ClassInstantiationException(this, parameters, e);
}
}


 Knock yourself out...

No comments:

Post a Comment