3
我的代碼在頂層模塊下面一行:如何通過反射正確實例化內部類?
String username = "[email protected]"
ModelBuilder userBuilder = utilityManager.getUtility("user").generateBuilder(username);
在我的「用戶」實用工具類,我有以下幾點:
private class UserBuilder extends ModelBuilder {
private final String username;
public UserBuilder(String username) {
this.username = username;
}
@Override
public User execute() {
return populateUserInformation(username);
}
}
@Override
public UserBuilder generateBuilder(Object... arguments) throws ReflectiveOperationException {
try {
return UserBuilder.class.getConstructor(String.class).newInstance((String) arguments[0]);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
throw new ReflectiveOperationException(e);
}
}
我試圖使用generateBuilder(對象... arguments)方法返回我的UserBuilder類的新實例(作爲模型構建器),但是,當我運行代碼時,出現以下異常:
nested exception is java.lang.ReflectiveOperationException: java.lang.NoSuchMethodException:
com.login.util.UserOperationsUtility$UserBuilder.<init>(java.lang.String)] with root cause
java.lang.NoSuchMethodException: com.login.util.UserOperationsUtility$UserBuilder.<init>(java.lang.String)
at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_66]
at java.lang.Class.getConstructor(Class.java:1825) ~[na:1.8.0_66]
我試圖遵循構造函數的java文檔,但我不知道如何調試。我對Java的反射能力的瞭解很少。