How to use multiple wildcards in an API call

158 Views Asked by At

I'm working with Anthill (an UrbanCode/IBM product) and one of the methods requires a parameter of type java.lang.Class<? extends SourceConfig<?>> sourceConfigType.

After reading the tutorial on generics I found that a class GitSourceConfig is a subclass of SourceConfig but I don't understand how the generic of SourceConfig<?> works in this context. Any ideas?

The end goal is to get a GitSourceConfig object and call the getRepositoryUrl/setRepositoryUrl methods. The Anthill Pro API is here and I'm looking at the SourceConfig class.

2

There are 2 best solutions below

3
On

The generic bounded wildcard type in your example java.lang.Class<? extends SourceConfig<?>> sourceConfigType specifies that sourceConfigType is any class that can be bound by the upper bound type of SourceConfig.

From the tutorial,

List<? extends Shape> is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.)

Note SourceConfig itself is also generic, and here it is using a regular unbounded wildcard.

1
On

Class is generic -- if you invoke getClass() on a String object result will be of type Class<String>.

In this case SourceConfig<R extends Repository> itself a generic so you have nested generics.

if you check definition of GitSourceConfig

public class GitSourceConfig extends SourceConfig<GitRepository> 

and

public class GitRepository extends Repository

so Class<GitSourceConfig> matches Class<? extends SourceConfig<?>>