Pavan
Pavan

Reputation: 159

Android: Android Support Annotations "RestrictTo"

I was understanding the android support annotations in which i came across "@RestrictTo" annotation; Which explains the different scopes developer can define. Can anyone explain in detail with some example how to use these annotations?

Any leads will be appreciated!

Upvotes: 10

Views: 8331

Answers (2)

Raghul Vaikundam
Raghul Vaikundam

Reputation: 588

RestrictTo annotation is used to restrict the scope of the variable to which it is annotated. Few scopes that are listed in the RestrictTo annotation are LIBRARY, LIBRARY_GROUP, TESTS, SUBCLASSES. When the variable is annotated with the restrictTo annotation, variable's attribute won't be listed as a suggestion in android studio.

For example, if I annotate the variable in the getter

@RestrictTo(RestrictTo.Scope.LIBRARY)
public @Nullable StudentInfo getInfo() {
  return mStudentInfo;
}

class StudentInfo {
     private String mAddress
     
     @RestrictTo(RestrictTo.Scope.LIBRARY)
     StudentInfo(String address) {
         mAddress = address
     }

     public String getAddress() {
         return mAddress
     }
}

In the above example since StudentInfo is restricted with the scope of LIBRARY, getAddress of the StudentInfo method won't be listed as a suggestion in IDE when called from outside the scope of the library.

Upvotes: -1

tynn
tynn

Reputation: 39853

It is used for meta programming access modifiers. Java will allow to access any public method from anywhere, while @RestrictTo applies to RestrictTo.Scope extends the accessing restrictions to other scopes not known to Java itself.

GROUP_ID
LIBRARY
LIBRARY_GROUP
SUBCLASSES
TESTS

Where for example SUBCLASSES would act like protected while being accessible from anywhere if the developer wants to.

Basically you could view it as suggestions, not any direct compiler enforcement.

Upvotes: 4

Related Questions