简体   繁体   中英

Is there a way to force a type argument to be provided when calling a generic/parameterized method?

Let's say I have a class and method like this:

public class Example {

    private final Map<String, Object> stuff = new HashMap<>();

    public <T> T getValue(String key) {
        return (T) stuff.get(key);
    }
}

Is it possible to force someone writing code that calls getValue() to explicitly provide a type witness to the method call?

Example example = new Example();
Boolean resultWithParameter    = example.<Boolean>getValue("some_key");

What I'd like to do is always require the parameter when calling the method. Is there a way to do that? I know I could always add a Class parameter but I was exploring other options.

There isn't a way to enforce it. Here is the structure of a method invocation as defined by the JLS .

MethodInvocation:
  MethodName ( [ArgumentList] )
  TypeName . [TypeArguments] Identifier ( [ArgumentList] )
  ExpressionName . [TypeArguments] Identifier ( [ArgumentList] )
  Primary . [TypeArguments] Identifier ( [ArgumentList] )
  super . [TypeArguments] Identifier ( [ArgumentList] )
  TypeName . super . [TypeArguments] Identifier ( [ArgumentList] )
ArgumentList:
  Expression {, Expression}

Specifically, your example refers to this one

Primary . [TypeArguments] Identifier ( [ArgumentList] )

example . <Boolean>       getValue   ( "some_key"     );

If you are not familiar with the notation , the most important part is this:

The syntax [x] on the right-hand side of a production denotes zero or one occurrences of x. That is, x is an optional symbol

So where [TypeArguments] (a type witness) is applicable, it is always optional; there is no way to enforce that it is present.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM