I'm learning how to create own annotations. I have read this: http://www.mkyong.com/java/java-custom-annotations-example/ but I have to pass all classes with my annotation - thats bad. So I have read this: https://stackoverflow.com/a/7665191/3279023 Unfortunately it throws an exception:
java.lang.NoSuchFieldException: No field mDexs in class Ldalvik/system/PathClassLoader; (declaration of 'dalvik.system.PathClassLoader' appears in /system/framework/core-libart.jar)
basicly:
Failed to get mDexs field
I want to create custom annotation Permission - and i did:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
String value() default "none";
}
Now, every time method with this annotation is run I want to check some conditions conditions and decide if method should be running... like:
@Permission(value = "testValue")
private void foo() {
// do stuff if permission allows
}
Why i want to do that? I think it will be good replacement for if statements:
private void foo() {
if(MyFooClass.STATIC_BOOLEAN_FIELD)
// do stuff
}
I have a lot of that if statement in my project and I want to get rid of it somehow
Is that even possible? And safe? And good idea?
I'm not sure it is a good idea, at least in terms of performance... But if you really want to do it, you just need reflection.
public void foo() {
Class<?> c = this.getClass(); // get the class object
Method m = c.getDeclaredMethod("foo"); // get the method
Permission p = m.getAnnotation(Permission.class); // get annotation
if (p!=null && p.value().equals("testValue") {
// do your test
}
else {
// do what you want
}
}
If you need to do this many times, you may use a static method boolean isAnnotated(String methodName)
for example. So that you just have to write a preamble in each concerned method : if (isAnnotated("foo")) {} else {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.