Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using unspecified generic wildcards in java

Tags:

java

generics

Im looking to implement a modular generic object factory in Java.

My code will comprise of three basic elements:

  1. A DataLoader, which will provide a generic Collection
  2. A factory, which, given an element T, returns an object of type U
  3. A class that ties the two together, and provides a Collection

The bit Im struggling with is that class 3 doesnt care about the type T. What does matter is that the factory and DataLoader use the same T - ie the raw data provided by the DataLoader should be usable by the builder to build the objects provided by the third class - but the third class doesnt care what that intermediate format is.

So how do I mandate that the generic type T is the same for 1 and 2 without that type being part of the specification of 3?

like image 379
PaulJWilliams Avatar asked May 29 '26 18:05

PaulJWilliams


1 Answers

One option is to use a helper class with two type parameters to bind the data loader and factory together, and then wrap that helper in another class that doesn't care about the original data loader's type:

public class DataLoader<T> {
    ...
}

public class Factory<T, U> {
    ...
}

public class Binder<T, U> {
    public Binder(DataLoader<T> dataLoader, Factory<T, U> factory) {
        ...
    }
}

public class ClassNumber3<U> {
    public ClassNumber3(Binder<?, U> binder) {
        ...
    }
}

You could even hide the existence of Binder from outside code by giving ClassNumber3 a generic constructor:

public class ClassNumber3<U> {
    Binder<?, U> binder;
    public <T> ClassNumber3(DataLoader<T> dataLoader, Factory<T, U> factory) {
        binder = new Binder<T, U>(dataLoader, factory);
        ...
    }
}
like image 61
Stuart Cook Avatar answered Jun 01 '26 09:06

Stuart Cook



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!