注解是如何保证注值的,原理是啥?

2017-04-25 13:01:27 +08:00
 esolve

我试了一下这篇文章里的注解 http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html 发现并没有能注值

1566 次点击
所在节点    问与答
7 条回复
esolve
2017-04-25 13:02:24 +08:00
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
String value() default "";
}



public class Apple {

@FruitName("Apple")
private String appleName;



public void setAppleName(String appleName) {
this.appleName = appleName;
}
public String getAppleName() {
return appleName;
}

public void displayName(){
System.out.println("水果的名字是:"+getAppleName());
}
}

这种没有能够注值啊
Cbdy
2017-04-25 13:37:09 +08:00
注解是 java 的一种元数据,本身不提供功能
esolve
2017-04-25 14:08:41 +08:00
@Cbdy 那注值是如何实现的?
LaudOak
2017-04-25 14:12:14 +08:00
要配合反射注值吧
esolve
2017-04-25 14:24:25 +08:00
@LaudOak 有没有原理分析的文章啊
大致是如何通过反射使得注解能够注值的。。
LaudOak
2017-04-25 15:22:25 +08:00
```
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

public class Reflect {

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FruitName {
String value() default "";
}

public static class Apple {
@FruitName("apple")
public String name;
}

public static void main(String... args) throws Exception {
Apple apple = new Apple();
Class clz = apple.getClass();
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(FruitName.class)) {
field.set(apple, field.getAnnotation(FruitName.class).value());
}
}
System.out.println(apple.name);
}

}

```

http://tutorials.jenkov.com/java-reflection/annotations.html
https://keyholesoftware.com/2014/09/15/java-annotations-using-reflection/
http://www.journaldev.com/1789/java-reflection-example-tutorial
https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html
aristotll
2017-04-25 16:30:30 +08:00
RetentionPolicy.RUNTIME 的通过反射来取

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/357217

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX