在学习 java9 StringConcatFactory
类时,我无法理解为什么使用 MethodHandles.publicLookup()
后的代码会抛出 StringConcatException
异常,而如果 MethodHandles.lookup()
使用一切正常。
根据查找的 java 文档:
"lookup - Represents a lookup context with the accessibility privileges of the caller"
StringConcatFactory.makeConcat(MethodHandles.publicLookup(),
"abc",MethodType.methodType(String.class));//Exception Here
StringConcatFactory.makeConcat(MethodHandles.lookup(),
"abc", MethodType.methodType(String.class)); //Working fine
我不确定我哪里弄错了?请帮助我理解这种行为。
最佳答案
makeConcat
的 javadoc 说明了第一个参数:
lookup Represents a lookup context with the accessibility privileges of the caller
publicLookup
返回的查找上下文没有这些权限。
即使你不连接任何东西,仍然会抛出异常:
MethodType concatType = MethodType.methodType(String.class); // No arguments, returns String
StringConcatFactory.makeConcat(MethodHandles.publicLookup(), "abc", concatType); // Exception
因为在StringConcatFactory#doStringConcat
中检查了context的访问权限:
if ((lookup.lookupModes() & MethodHandles.Lookup.PRIVATE) == 0) {
throw new StringConcatException("Invalid caller: " +
lookup.lookupClass().getName());
}
上下文需要私有(private)查找模式,而 publicLookup
没有:
System.out.println((MethodHandles.publicLookup().lookupModes()
& MethodHandles.Lookup.PRIVATE) != 0); // false
System.out.println((MethodHandles.lookup().lookupModes()
& MethodHandles.Lookup.PRIVATE) != 0); // true
关于java - StringConcatFactory 中的异常 - Java 9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46048988/