package ann;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Inject {
String value() default "key";
}
这个是注解
package ann;
public class Test {
@Inject(value = "hello world") public String value;
public void printValue() {
System.out.println(value);
}
}
这个是用注解的类
package ann;
import java.lang.reflect.Field;
public class AnnTest {
public static void setAnn() throws Exception {
Class cls = Test.class;
Field field = cls.getField("value");
Inject i = field.getAnnotation(Inject.class);
Test t = new Test();
field.set(t, i.value());
t.printValue();
}
public static void main(String[] args) throws Exception {
AnnTest.setAnn();
}
}
这个是解析用的field.set(t, i.value());可以换成任何你要做的事
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Inject {
String value() default "key";
}
这个是注解
package ann;
public class Test {
@Inject(value = "hello world") public String value;
public void printValue() {
System.out.println(value);
}
}
这个是用注解的类
package ann;
import java.lang.reflect.Field;
public class AnnTest {
public static void setAnn() throws Exception {
Class cls = Test.class;
Field field = cls.getField("value");
Inject i = field.getAnnotation(Inject.class);
Test t = new Test();
field.set(t, i.value());
t.printValue();
}
public static void main(String[] args) throws Exception {
AnnTest.setAnn();
}
}
这个是解析用的field.set(t, i.value());可以换成任何你要做的事