I'm studying this piece of code and got stucked in the commented row:
protected <T> T creaOggetto(Class<T> classe, int id) {
try {
Package pacchetto = classe.getPackage();
String nomePacchetto = pacchetto.getName();
String nomeClasse = classe.getSimpleName();
String nomeClasseRisultato = nomePacchetto + ".impl." + nomeClasse + "Impl";
Class<?> classeRisultato = Class.forName(nomeClasseRisultato);
Constructor<?> costruttore = classeRisultato.getConstructor(new Class[] {int.class});
@SuppressWarnings("unchecked")
T risultato = (T)costruttore.newInstance(new Object[] {id});
return risultato;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
I know that getConstructor()
returns the constructor object for that class but (new Class[] {int.class})
confuses me, what is his purpose?
According Java docs:
public Constructor<T> getConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.
So, classeRisultato.getConstructor(new Class[] {int.class});
returns the constructor that accepts one and only one int
parameter or NoSuchMethodException
if it doesn't exist.
In code you posted, note that, using that constructor, it creates a new instance of that class passing the id
, that is the actual int
argument:
T risultato = (T)costruttore.newInstance(new Object[] {id});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With