是否可以判断方法的参数是否为final
?
我已经尝试过:
int modifiers = method.getParameters()[0].getModifiers() // modifiers == 0
但即使第一个参数具有 final
修饰符,modifiers
也会设置为零。
编辑:我真的不认为我的问题是重复的。当我使用类成员(例如字段、方法等)尝试此代码时,它运行得很好。但是使用方法参数 getModifiers
失败!
edit2:在你建议我类似的问题中,我没有找到答案......所以你能帮助我,如何检查参数是否是最终的?
最佳答案
简单研究了一下,恐怕不太可能。请参阅对此的第一条评论 question
If you looked at a decompiled class, you could see that the compiler erases the final keyword from all final parameters. And it is reasonable because the final makes sense only at compile time.
我试图找到更多这方面的证据,但失败了。无论如何,我根据第一个建议的杜比答案做了一个小测试。
有类似的测试类
public class TestClass {
public void testMethod(final Integer param) {} // could be also int
}
并运行此测试/日志记录
@Test
public void testIsFinal() throws NoSuchMethodException, SecurityException {
Method method = TestClass.class.getMethod("testMethod", Integer.class);
log.info("method {}", method);
Parameter[] params = method.getParameters();
log.info("params {}", params);
log.info("params[0] {}", params[0]);
log.info("modifiers {}", params[0].getModifiers());
log.info("final {}", Modifier.isFinal( params[0].getModifiers() ));
}
日志
2017-12-11 13:11:24.512 INFO org.example.jpa.JUnitTest:33 - method public void org.example.jpa.JUnitTest$TestClass.testMethod(java.lang.Integer)
2017-12-11 13:11:24.521 INFO org.example.jpa.JUnitTest:36 - params[0] java.lang.Integer arg0
2017-12-11 13:11:24.521 INFO org.example.jpa.JUnitTest:37 - modifiers 0
2017-12-11 13:11:24.522 INFO org.example.jpa.JUnitTest:38 - final false
因此,编译的方法声明中似乎不存在唯一允许的方法参数修饰符final
。请注意,它既不存在于记录的方法签名中
public void org.example.jpa.JUnitTest$TestClass.testMethod(java.lang.Integer)
public static final int FINAL = 0x00000010;
和
/**
* The Java source modifiers that can be applied to a method or constructor parameter.
* @jls 8.4.1 Formal Parameters
*/
private static final int PARAMETER_MODIFIERS = Modifier.FINAL;
和
public static boolean isFinal(int mod) {
return (mod & FINAL) != 0;
}
因此,为了表明方法参数已声明为 final
,第二位应为 1。
关于java - 是否可以通过反射来确定方法参数是否是最终的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47737745/