使用带有Enum的构造函数反射实例化类

时间:2017-02-17 20:14:03

标签: java reflection constructor enums

我有一个超类OpCode和子类Add / And..etc

我试图反思性地根据它们的类名字符串构造子类。构造函数采用超类中定义的枚举。

我在尝试:

OpCode theOpCode = (OpCode) Class.forName("com.sstangle.opCodes." + opCodeName).getConstructor(OpCode.OpEn.class).newInstance(opEn);

导致

java.lang.NoSuchMethodException: com.sstangle.opCodes.Add.<init>(com.sstangle.opCodes.OpCode$OpEn)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getConstructor(Unknown Source)

添加类是

public class Add extends OpCode {
    Add(final OpEn opEn) {
        super(opEn);
        this.assemblyCommand = "ADD";
    }
}

OpCode类是

public abstract class OpCode {
    OpCode(final OpEn opEn) {
        this.opEn = opEn;
    }
    public static enum OpEn {
        I, MI, MR, RM, ZO
    }
}

如何使用枚举正确访问构造函数?

由于

1 个答案:

答案 0 :(得分:3)

查看source code of Class.getConstructor

public Constructor<T> getConstructor(Class<?>... parameterTypes)
    throws NoSuchMethodException, SecurityException {
    checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
    return getConstructor0(parameterTypes, Member.PUBLIC);
}

Member.PUBLIC告诉getConstructor0方法只返回公共构造函数。

private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
                                    int which) throws NoSuchMethodException
{
    Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
    for (Constructor<T> constructor : constructors) {
        if (arrayContentsEq(parameterTypes,
                            constructor.getParameterTypes())) {
            return getReflectionFactory().copyConstructor(constructor);
        }
    }
    throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
}

其中privateGetDeclaredConstructors采用名为publicOnly的布尔参数:

private Constructor<T>[] privateGetDeclaredConstructors(boolean publicOnly)

制作构造函数public,或改为使用getDeclaredConstructor