Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a generic method directly?

Tags:

java

generics

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();
like image 670
dalawh Avatar asked Dec 13 '25 01:12

dalawh


1 Answers

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.

like image 157
Sotirios Delimanolis Avatar answered Dec 15 '25 15:12

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!