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 AnnotationPractice {
public static void main(String[] args) throws IllegalAccessException {
City city = new City("重庆", "重庆不夜城", 3000);
check(city);
}
static void check(City city) throws IllegalAccessException {
for (Field field : city.getClass().getFields()) {
Range range = field.getAnnotation(Range.class);
if (range == null) {
continue;
}
Object value = field.get(city);
int number = value instanceof String s ?
s.length() :
value instanceof Integer years ? years : -1;
if (number != -1)
isIn(range.min(), range.max(), number, field);
}
}
static void isIn(int leftNum, int rightNum, int number, Field field) {
if (number < leftNum || number > rightNum) {
throw new IllegalArgumentException("Invalid field: " + field.getName());
}
}
}
class City {
@Range(min = 2, max = 20)
public String cityName;
@Range(min = 1, max = 50)
public String citySongName;
@Range(min = 1, max = 10000)
public float YearsOfHistory;
public City(String cityName, String citySongName, int yearsOfHistory) {
this.cityName = cityName;
this.citySongName = citySongName;
YearsOfHistory = yearsOfHistory;
}
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Range {
int min() default 0;
int max() default 255;
}
1905