Android: Android Support Annotations "RestrictTo"
Asked Answered
S

2

10

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!

Surcease answered 27/4, 2017 at 11:34 Comment(0)
A
3

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.

Auraaural answered 27/4, 2017 at 11:46 Comment(4)
I was trying to use this annotation to block method call of my library project from another project. Is this the right scenario in which i am using it? But it didn't work.Surcease
I would say so.Auraaural
But if method is annotated with @RestrictTo, regardless it is public you cannot call that method.Roeder
I am able to call the method from another project in which i have used the library.Surcease
C
-1

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.

Commendam answered 18/7, 2019 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.