dalawh
dalawh

Reputation: 924

How to call a generic method directly?

Here is the method I am calling:

public static <T extends Something> Group<T> getGroup() { ... }

If I wanted to store the result in a variable, I would do something like this:

Group<SomethingSubClass> group = StaticClass.getGroup();

How would I call the method without storing it in a variable?

StaticClass.getGroup();

The above is what I tried, but I am unsure (mostly don't think it is possible from the way my method is) to add the generic type T.

Solution:

StaticClass.<SomethingSubClass>getGroup();

Upvotes: 3

Views: 125

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280181

You don't need anything special. Just invoke it as

StaticClass.getGroup();

You will simply be ignore the return value. The type argument will be inferred as Something, which is what you'd have access to in your method anyway.

You would specify an actual type argument by doing

StaticClass.<SomeTypeThatExtendsSomething>getGroup();

but you don't need that since the only part of your method that makes use of the generic type is the return type, which you are discarding.

Upvotes: 1

Related Questions