Java注解
-
jdk1.5之后添加的新功能,很多框架为了简化代码,都使用注解。可以理解为插件,为代码级别的插件,@xxx卸载类方法上,注解不会也不能影响代码的逻辑。
-
分为 内置注解,与自定义注解
-
内置注解
@Override 重写 @Deprecated过时 @SupressWarning去除警告
@Target(value=ElementType.METHOD)//表示使用反射的范围
@Retention(RetentionPolicy.RUNTIME)//允许反射获取信息 -
自定义注解
package zx.lol.anotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value=ElementType.METHOD)//表示使用反射的范围
@Retention(RetentionPolicy.RUNTIME)//允许反射获取信息
public @interface AnnotationT1 {
String value();
int Aid();
String[] arr ();
}
class AnnDemo{
private String name;
@AnnotationT1(value = "zxtest1",Aid = 12,arr = {"123","456"})//属性值根据自定义注解类中属性值给定
public void add() {
}
}
- 自定义注解类可以默认属性值
public @interface AnnotationT1 {
String value() default "1213";
int Aid() default 123;
String[] arr ();
}
使用注解实现ORM框架映射
- 实体类的属性命名,username,userage。
- 数据库命名 user_name,user_age。
orm对象关系映射实现select user_name,user_age from user_table。
首先定义注解
- 定义SetTable注解类
package zx.lol.orm;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SetTable {
String value();
}
- 定义SetProperty注解类
package zx.lol.orm;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface SetProperty {
String name();
int len();
}
- 定义一个userentity,用来插入注解
package zx.lol.orm;
@SetTable("user_table")
public class userEntity{
@SetProperty(name = "user_name",len = 10)
private String username;
@SetProperty(name="user_age", len = 10)
private int userage;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getUserage() {
return userage;
}
public void setUserage(int userage) {
this.userage = userage;
}
}
- 定义一个测试类
package zx.lol.orm;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
//1.项目使用注解,必定使用反射
Class<?> forname = Class.forName("zx.lol.orm.userEntity");
/*
* Annotation[] annotations = forname.getAnnotations();//获取某一个类上使用那些注解 for
* (Annotation annotation : annotations) { System.out.println(annotation); }
*/
Field[] fields = forname.getDeclaredFields();
StringBuffer sf = new StringBuffer();
sf.append("select ");
for(int i = 0;i<fields.length;i++ ) {
SetProperty setProperty = fields[i].getAnnotation(SetProperty.class);
String property = setProperty.name();
sf.append(property);
if (i==fields.length-1) {
sf.append(" from ");
}else {
sf.append(",");
}
}
//获取注解对象
SetTable setTable = forname.getAnnotation(SetTable.class);
String tablename = setTable.value();
sf.append(tablename);
System.out.println(sf);
}
}
- 运行结果成功
select user_name,user_age from user_table