Silta
Silta

Reputation: 99

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

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.

Upvotes: 2

Views: 578

Answers (1)

heiwil
heiwil

Reputation: 669

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
        }

    }
}

Upvotes: 2

Related Questions