我在顶层模块中有以下代码行:
String username = "testuser987-abc-zyx@gmail.com"
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(Object... arguments) 方法返回我的 UserBuilder 类的新实例(作为 ModelBuilder),但是,当我运行代码时出现以下异常:
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 的反射功能知之甚少。
最佳答案
问题在 getConstructor
中明确指定文档:
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.
在这种情况下,您有一个内部的、非static
类。实际上,您还需要在编译时通过封闭类的实例来限定 UserBuilder
对象的实例化,使用反射时也是如此。您有两个选择:
- 将
类
设为静态 - 查找正确的构造函数并传递封闭实例
后者很容易做到:
Constructor c = UserBuilder.class.getConstructor(UserOperationsUtility.class, String.class);
return c.newInstance(this, (String)args[0]);
关于java - 如何通过反射正确实例化内部类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881454/