I was checking out all the new utility methods introduced in String
class since java 8 and found this one method resolveConstantDesc
which apparently takes a MethodHandles.Lookup
as input.
However, the method simply ignores the input and returns the same instance.
/**
* Resolves this instance as a {@link ConstantDesc}, the result of which is
* the instance itself.
*
* @param lookup ignored
* @return the {@linkplain String} instance
* @since 12
*/
@Override
public String resolveConstantDesc(MethodHandles.Lookup lookup) {
return this;
}
I don't quite understand the use of this. Where will this be helpful? What are it's use cases?
This method is required by the ConstantDesc
interface that String
implements.
ConstantDesc
is part of the java.lang.constant
package. The package description says
Classes and interfaces to represent nominal descriptors for run-time entities such as classes or method handles, and classfile entities such as constant pool entries or invokedynamic call sites. These classes are suitable for use in bytecode reading and writing APIs, invokedynamic bootstraps, bytecode intrinsic APIs, and compile-time or link-time program analysis tools.
So if you are not writing any of those things, you don't need to worry about this method.
A ConstantDesc
just represents an entry in the constant pool of a class file. String
implements it because strings are one of the things that can go in the constant pool. Others include Integer
, Double
, ClassDesc
, MethodTypeDesc
etc. Integers, doubles, classes and methods are all things that can go in the constant pool. See also the Constant Pool section of the JVMS.
The point of resolveConstantDesc
is that, given an entry in the constant pool (this
), please turn it into an actual object at runtime. For String
, this is trivially just the String
itself. For ClassDesc
, resolveConstantDesc
returns a Class<?>
, and for MethodTypeDesc
it might return a MethodType
. See an example of how this is implemented for a class here.
The point of the Lookup
parameter is to enforce access control among other things. Again, for String
, this is ignored because string constants are accessible from anywhere. For ClassDesc
however, the class referenced by the constant pool entry might not be accessible from certain places. MethodHandles.Lookup
can be used to enforce these things. Read its documentation if you are interested.