NotNull Annotationを作り、NotNullチェックする
annotationで指定したメッセージを表示する
class定義からgetDeclaredFieldsでfield定義を取り出している
f.get(x(instance))でxから値取得する。
これをリフレクションという。
@Retention(RetentionPolicy.RUNTIME)
@interface NotNull{
String message();
}
class Sample {
@NotNull(message = " is not null x1")
private String name;
@NotNull(message = " is not null x2")
private String category;
private String city;
public Sample(String name, String category, String city) {
this.name = name;
this.category = category;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
public class Outer {
public static void main(String args[]) {
Sample s = new Sample(null,null,null);
method(s);
s = new Sample("",null,null);
method(s);
}
static void method(Sample s) {
System.out.println("-------------");
Field[] fs = s.getClass().getDeclaredFields();
for(Field f : fs) {
f.setAccessible(true);
NotNull n = f.getAnnotation(NotNull.class);
if(n!=null) {
String msg = n.message();
String name = "";
String fieldName = "";
try {
fieldName = f.getName();
name = (String) f.get(s);
} catch (IllegalAccessException ex ) {
ex.printStackTrace();
}
if(name == null) {
System.out.println(fieldName + msg);
}
}
}
}
}
-------------
name is not null x1
category is not null x2
-------------
category is not null x2