获取参数修饰符反射

时间:2016-03-14 23:05:50

标签: java reflection

我有一个 SimplePojo 类,我想使用反射运行时检索参数修饰符。

然而,它似乎不起作用...... SSCEE

public final class SimplePojo {

    private final String name;
    private final int age;

    public SimplePojo(String name, final int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {

    }

    public int getAge() {
        return age;
    }
}

这就是我尝试检查参数修饰符是否为 FINAL

的方法
for (Class<?> paramClazz : method.getParameterTypes()) {
            if (!Modifier.isFinal(paramClazz.getModifiers())) {
                throw new ConstraintViolationException(
                        String.format("Parameters of method '%s' in '%s' must be declared as 'final'",
                                method.getName(),
                                point.getTarget().getClass().getCanonicalName()
                        )
                );
            }
        }

编辑:

//are all constructors params final
        for (Constructor constructor : clazz.getConstructors()) {
            for (Class<?> constructorParam : constructor.getParameterTypes()) {
                Log.e(TAG, "constructorParam:" + constructorParam.getName() + ", mod: " + constructorParam.getModifiers());
                if (!Modifier.isFinal(constructorParam.getModifiers())) {
                    throw new ConstraintViolationException(
                            String.format("Constructor parameters in '%s' annotated with '%s'" +
                                            " must be declared as 'final'",
                                    clazz.getCanonicalName(),
                                    Inmutable.class.getSimpleName()
                            )
                    );
                }
            }
        }

并输出:

constructorParam:java.lang.String, mod: 17
constructorParam:int, mod: 1041

2 个答案:

答案 0 :(得分:2)

假设您使用的是Java 8,则可以使用This post方法获取Method的形式参数。

这将返回Parameter个实例的数组,您可以在其上调用Executable.getParameters()

我不相信有一个标准的Java 8之前的解决方案。

答案 1 :(得分:-2)

getModifiers返回一组标记。

试试这个:

final int FINAL = 0x0010;

if (!(paramClazz.getModifiers() & FINAL)) {
   throw new ...
相关问题