In a library I am developing I have a factory method that looks a bit like:

public <T> T instantiate(Type targetType) {
    return ...;
}

I am using a type parameterized method to avoid that users of my library have to cast every time they invoke it (that would be the case if I would have chosen to return Object).

Is there any reason this is not a good design choice ?.

I do not like that the programmer can invoke my method like:

String s = instantiate(Integer.class);

Which is clearly wrong.

Unfortunately, the method requires a type and not a class, otherwise I could have written something like:

public <T> T instantiate(Class<T> targetClass) {
    return ...;
}

没有正确的解决方案

许可以下: CC-BY-SA归因
scroll top