我正在学习如何创建自己的注释。我读过这个:http://www.mkyong.com/java/java-custom-annotations-example/ 但我必须通过我的注释传递所有类 - 这很糟糕。所以我读过这个:https://stackoverflow.com/a/7665191/3279023 不幸的是它抛出了一个异常:
java.lang.NoSuchFieldException: No field mDexs in class Ldalvik/system/PathClassLoader; (declaration of 'dalvik.system.PathClassLoader' appears in /system/framework/core-libart.jar)
基本上:
Failed to get mDexs field
我的目标:
我想创建自定义注释权限 - 我做到了:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Permission {
String value() default "none";
}
现在,每次运行带有此注释的方法时,我想检查一些条件并决定方法是否应该运行...例如:
@Permission(value = "testValue")
private void foo() {
// do stuff if permission allows
}
我为什么要这么做?我认为它将是 if 语句的良好替代品:
private void foo() {
if(MyFooClass.STATIC_BOOLEAN_FIELD)
// do stuff
}
我的项目中有很多 if 语句,我想以某种方式摆脱它
这可能吗?安全吗?好主意吗?
最佳答案
我不确定这是一个好主意,至少在性能方面......但如果你真的想这样做,你只需要反射(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
}
}
如果您需要多次执行此操作,您可以使用静态方法 boolean isAnnotated(String methodName)
例如。这样您只需在每个相关方法中编写一个序言:if (isAnnotated("foo")) {} else {}
关于java - Android 创建自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909795/