实体类是用注解方式映射的
那么就可以考虑采用反射方式来做了
你通过反射拿到你的那些@Column和@Table注解,然后拿到里边的属性,不就可以拼了吗
package org.qxh.jdk15.annotation;
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.TYPE,ElementType.METHOD})
public @interface MyAnnotation {
String color() default "blue";
String value();
}
属性的定义方式就跟接口里的方法一样,可以有默认值,其中的value属性比较特殊,一般我们写属性的时候都是@MyAnnotation(color=”red”,value=”test”)
属性名=属性值,但是我们上面的color有默认值了,所以就可以使用默认值,属性名如果是value就可以省略value=这部分而写作:@MyAnnotation(”test”)
package org.qxh.jdk15.annotation;
@MyAnnotation("test")
public class ClassUseAnnotation {
public static void main(String[] args) {
if(ClassUseAnnotation.class.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation myAnnotation = ClassUseAnnotation.class.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.color());
System.out.println(myAnnotation.value());
}
}
}
@MyAnnotation("test")这部分我们完全可以写成:@MyAnnotation(color = "red",value = "test")不过如果你的颜色就打算采用默认值的话就没必要这么写了。另外取得属性值得时候就跟调用方法的方式是一样的:
System.out.println(myAnnotation.color());
System.out.println(myAnnotation.value());
楼主说的很经典
2011年10月09日 13:26