Java Annotation简单例子

public class AnnotationTest {

	@FruitName("水果:")
	public static String fruit = "Apple";
	
	public static String string = "a";
	
	public static void main(String[] args) {
		AnnotationTest test = new AnnotationTest();
		AnnotationProvider.parserAnnotation2(test);
		System.out.println(fruit);
		System.out.println(string);
		System.out.println(test.fruit);
		System.out.println(test.string);
	}
}


public class AnnotationProvider {

	public static void parserAnnotation(Object object) {
		Class class1 = object.getClass();
		Field[] fields = class1.getDeclaredFields();
		for(Field field : fields) {
			FruitName fruitName = field.getAnnotation(FruitName.class);
			try {
				if (fruitName != null) {
					String value = (String) field.get(object);
					field.set(object, fruitName.value() + value);
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static void parserAnnotation2(Object object) {
		Class class1 = object.getClass();
		Field[] fields = class1.getDeclaredFields();
		for(Field field : fields) {
			Annotation[] annotations = field.getAnnotations();
			for (Annotation annotation : annotations) {
				if (annotation instanceof FruitName) {
					String value;
					try {
						value = (String) field.get(object);
						field.set(object, ((FruitName)annotation).value() + value);
					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}
}

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


你可能感兴趣的:(java,android)