java - User Defined Annotations -
i new user defined annotations. trying create own annotation @notnull annotation.
i want annotation on method , want method executed if satisfies conditions.
here code:
@target({ elementtype.method}) @retention(retentionpolicy.runtime) public @interface policycheck{ string[] policies(); } i want use this:
@policycheck(policies = {"p1", "p2"}) public void dosomething(){ } when call on method provided policies, if satisfies condition, must run method.
correct me if wrong usage of annotations , please tell if possible. stuck write logic behind it.
thanks.
annotations can evaluated @ runtime or compile time, method choose depends on actual use case.
at runtime using reflections: mentioned in comments, need proxy class. need intercept calls annotated method, check policies , either call real method or throw exception example. java provides proxy class, check permissions inside invocationhandler. let user use dependency injection or provide method handles creation of proxy.
example method this: foo foo = yourannotationlibrary.createproxy(foo.class);
another way use annotation processor can run when user compiles code. useful static checks, assuring parameter types on annotated methods - won't able check null arguments occur @ runtime. generate proxy classes though enforce policies @ runtime.
using reflections less complicated. if annotation processing applicable use case, may more convenient user because nicely integrates modern ides show warnings, errors or additional information directly on elements in source code editor , can prevent many errors before application run.
Comments
Post a Comment