我试了一下这篇文章里的注解 http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html 发现并没有能注值
1
esolve OP @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()); } } 这种没有能够注值啊 |
2
Cbdy 2017-04-25 13:37:09 +08:00
注解是 java 的一种元数据,本身不提供功能
|
4
LaudOak 2017-04-25 14:12:14 +08:00 via Android
要配合反射注值吧
|
6
LaudOak 2017-04-25 15:22:25 +08:00 1
```
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 |
7
aristotll 2017-04-25 16:30:30 +08:00
RetentionPolicy.RUNTIME 的通过反射来取
|