Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.getConstructor function parameters

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?

like image 861
Gerico0889 Avatar asked Sep 14 '25 23:09

Gerico0889


1 Answers

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});
like image 95
Héctor Avatar answered Sep 17 '25 13:09

Héctor