Amrmsmb
Amrmsmb

Reputation: 1

How to make a constructor of a generic type

given the the below code,how can i make the constructor of a generic type so that it can accept any class passed to it

code:

ServiceCtrl(Context ctx, Class<SPPService> sppServiceClass) {
    this.mCtx = ctx;
    this.mClass = sppServiceClass;
}

public boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) this.mCtx.getSystemService(this.mCtx.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (this.mClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

Upvotes: 1

Views: 81

Answers (2)

Ga&#235;l J
Ga&#235;l J

Reputation: 15090

Do you mean, make sppServiceClass generic in the constructor ?

If so, you're looking for this :

ServiceCtrl(Context ctx, Class<?> clazz) {
    ...
}

EDIT : you need to change the declaration of mClass as well to Class<?>.

Upvotes: 1

Berkay Turancı
Berkay Turancı

Reputation: 3459

public class ServiceCtrl<E extends Object> {
    private Class<E> mClass;

    ServiceCtrl(Context ctx, Class<E> sppServiceClass) {
        this.mCtx = ctx;
        this.mClass = sppServiceClass;
    }

    public boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) this.mCtx.getSystemService(this.mCtx.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (this.mClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

Upvotes: 1

Related Questions