1
public static <T extends Context> APIInterface getServiceInstance(T context) {

    if (apiInterface == null) {

      // do Something
    }

    return apiInterface;
}

This method is currently accepting all the objects .. Activity.this .. getApplicationContext(), getContext() and getBaseContext()

Can we restrict this method to only accept Context object as a parameter / not Activity.

Thanks

Paranoid
  • 214
  • 2
  • 14
  • [`Context` is `abstract`](https://developer.android.com/reference/android/content/Context). The only instances you can have will be of subclasses. – Mike M. Mar 12 '20 at 08:31
  • i m ok with these methods getApplicationContext(), getContext() and getBaseContext(). But not activity object. Is there any method we can bound/restrict parameter. – Paranoid Mar 12 '20 at 08:40
  • This implementation is correct, activity is also a subclass of Context – Lakhwinder Singh Mar 12 '20 at 09:03

1 Answers1

0
if (!context instanceof Activity) {
      //Your code
   }else{
      throw new RuntimeException("Text exception");
  }

This code verifies that context is not an activity context.

Destroyer
  • 785
  • 8
  • 20
  • I can do this verification inside the method body.But I m talking about to restrict parameter itself. So then if someone call this methods like this getServiceInstance (Activity.this). He must get compile time error. How i can achieve this :). – Paranoid Mar 12 '20 at 08:55
  • I'm afraid this is impossible, it would be better if you check if the context is not an activity context, otherwise throw an exception – Destroyer Mar 12 '20 at 08:56
  • Why don't you want to do type checking and throw an exception otherwise? – Destroyer Mar 12 '20 at 09:01
  • The problem in your method is if i will call this method 200 times in my project on different classes. i need to handle that exception every where. Alternative i can find. But i was thinking that may be i can get some efficient approach here. And secondly with your above code we will get compile time error. Little modification need if (!(context instanceof Activity)) { } else throw new RuntimeException(""); – Paranoid Mar 12 '20 at 09:27
  • why do you need to check the activity context? – Destroyer Mar 12 '20 at 09:36
  • As we know in android we have different context. Some Resources are related to Application Context and Some Resources are related to Activity Context and so on. So if i only want to call those resources in this method that's a part of application context. So that's why i was trying to do this . :) – Paranoid Mar 12 '20 at 09:41
  • why don’t you just get the application context out of the ordinary context? – Destroyer Mar 12 '20 at 09:56