javagenericsconstructortype-bounds

Can I force a constructor to put a stricter bound on its generic type?


In java, generic classes have constructors to construct instances of some generic type. This is simple, and callers of the constructor can specify any type that is within bounds.

Is it possible to have a constructor that puts stricter bounds on that generic type?
E.g., have a constructor that forces the generic type to be String.

public class GenericClass<T extends Serializable> {
    public GenericClass() {
        // normal constructor
    }

    public GenericClass(String argument) {
        // Can I force this constructor to construct a `GenericClass<String>`?
    }
}

// The first constructor can have any type
GenericClass<String> stringInstance = new GenericClass<>();
GenericClass<Integer> intInstance = new GenericClass<>();

// The second constructor is limited to `GenericClass<String>`
stringInstance = new GenericClass<>("with generic type String is okay");
intInstance = new GenericClass<>("with other generic type is not okay");

I would like to have the last line fail because of incompatible types.

Is this possible?


Solution

  • One way to cause the last line to fail is this:

    public class GenericClass<T extends Serializable> {
        public GenericClass() {
            // normal constructor
        }
    
        public GenericClass(T argument) {
    
        }
    }
    

    But obviously that doesn't stop people from calling new GenericClass<>(1).

    Alternatively, you can write a factory method ofString:

    public static GenericClass<String> ofString(String s) {
        GenericClass<String> gc = new GenericClass<>();
        // do stuff to gc
        return gc;
    }