Java - Use getService method who have Class<T> for parameter

DaJaime :

I have this method to get my services

public <T extends ServiceInterface> T getService(Class<T> aServiceClass);

I would like to instantiate the class "MyService" that extends to ServiceInterface with this method.

How to do that? should I make a new MyService object to pass it as a parameter? but if I do that the get service method will not be useful.

heiwil :

If I understand your question, you want to create a class MyService, that extends ServiceInterface. And you want to get your Service by the method getService(Class<T> aServiceClass>), right? That would look like this (but please split the classes in different files):

package test;

public class Test2 {

    public static void main(String[] args) {
        MyService m = getService(MyService.class);
        //m.someMethod(...);
    }

    public static <T extends ServiceInterface> T getService(Class<T> aServiceClass) {
        return null; //??
    }

    //class MyService
    public class MyService extends ServiceInterface{

        //someMethods...

    }

    //class ServiceInterface
    public class ServiceInterface {

        public <T extends ServiceInterface> T getService(Class<T> aServiceClass) {
            return null; //whatever the method is doing
        }

    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156666&siteId=1