简体   繁体   中英

Generic factory method and Class<T> parameter

I have a static factory method which signature looks like this:

public static <F, T extends Provider<F>> T getProvider(Class<T> clazz)

I'm trying to implement method that returns Class<T> object which is a parameter for getProvider mentioned above. However definition like this doesn't work:

public <F, T extends Provider<F>> Class<T> getProviderClass() {
       return DefaultProvider.class;
}

What would you suggest?

 public Class<T> getProviderClass() {
    Type superClass = getClass().getGenericSuperclass();
    ParameterizedType type = (ParameterizedType) superClass;
    Type[] types = type.getActualTypeArguments();
    Class<T> providerClass = (Class<T>) types[0];
    return providerClass;
 }

You could also take this code and place it in the constructor, set an instance variable of Class to the value provided by this method so you have easier and more performance happy access to it for the rest of your usage within the generic factory.

You would need to pass in a Class object and do something with it to find the correct DefaultProvider.class

You can't have a universal factory class. Each type needs to have it's own concrete factory somewhere. One good pattern is to have the class provide it's own default factory via a static method.

MyClass.getProvider()

Where you have MyClass and MyClassDefaultProvider defined and getProvider returns an instance of MyClassDefaultProvider

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM