我正在研究这段代码并卡在注释行中:
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;
}
我知道 getConstructor()
返回该类的构造函数对象,但是 (new Class[] {int.class})
让我很困惑,他的目的是什么?
最佳答案
根据 Java 文档:
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.
因此,classeRisultato.getConstructor(new Class[] {int.class});
返回接受一个且仅一个 int
参数或 NoSuchMethodException 的构造函数
如果它不存在。
在您发布的代码中,请注意,使用该构造函数,它会创建该类的一个新实例并传递 id
,即实际的 int
参数:
T risultato = (T)costruttore.newInstance(new Object[] {id});
关于java - Class.getConstructor函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48668919/