Javaカスタムコメント
Java注釈は現在広く使われている。springにおける注釈による依存注入、Spring Web MVCにおけるRoute、PlayFrame eworkにおける注釈によるValidationなど。
注釈を使って、XMLの煩雑さを適当なところで代替できます。
今はどうやってコメントをカスタマイズしますか?
ターゲット:属性のデフォルト値を注釈で定義します。たとえば:
注釈を使って、XMLの煩雑さを適当なところで代替できます。
今はどうやってコメントをカスタマイズしますか?
ターゲット:属性のデフォルト値を注釈で定義します。たとえば:
public class DefaultUse {
@Default(value = "Hello Annotation")
private String msg;
public void say(){
System.out.println(msg);
}
}
一、Annotationの新規作成import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Retention
* CLASS: , VM 。
* RUNTIME: , VM , 。
* SOURCE: 。
*/
@Retention(RetentionPolicy.RUNTIME)
/**
* @Target
* , Target ,
* 。
* ElementType.ANNOTATION_TYPE:
* ElementType.CONSTRUCTOR:
* ElementType.FILED:
* ElementType.LOCAL_VARIABLE:
* ElementType.METHOD:
* ElementType.PACKAGE:
* ElementType.PARAMETER:
* ElementType.TYPE: 、
*/
@Target(ElementType.FIELD)
public @interface Default {
String value(); //
}
二、実際類で使用するpublic class DefaultUse {
@Default(value = "Hello Annotation")
private String msg;
public void setMsg(String msg) {
this.msg = msg;
}
public void say(){
System.out.println(msg);
}
}
三、注釈解析過程import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class DefaultTest {
public static void main(String args[]) throws Exception{
DefaultUse use = new DefaultUse();
//Default
//
Field[] fileds = use.getClass().getDeclaredFields();
for(Field filed : fileds){
Default annotation = filed.getAnnotation(Default.class);
if(annotation != null){
PropertyDescriptor pd = new PropertyDescriptor(filed.getName(), DefaultUse.class);
Method setterName = pd.getWriteMethod();
if(setterName!=null){
String value = annotation.value();
filed.setAccessible(true);
setterName.invoke(use, value);
}
}
}
use.say();
}
}