二十二、枚举和注释
« 上一篇
  个人整理非商业用途,欢迎探讨与指正!!
文章目录
- 二十二、枚举和注释
 - 22.1枚举
 - 22.2注解
 
22.1枚举
接口/类中的静态属性
 以内部类的形式使用较多
public enum Color {RED,GREEN,YELLOW
}
class Test01 {public static void main(String[] args) {Color c = Color.RED;switch(c) {case RED:System.out.println("红色的.");break;case GREEN:System.out.println("绿色的");break;case YELLOW:System.out.println("黄色的");break;}}
}
public class User {public static void main(String[] args) {User user = new User();user.setGender(Gender.BOY);user.setRole(Role.ADMIN);System.out.println(user);}private int userId;private String username;private String password;private Gender gender;private Role role;//	内部枚举类型就是为gender赋值的private enum Gender {GIRL,BOY}
//	role赋值的private enum Role {ADMIN,NORMAL,SUPERADMIN,QISHOU}...
 
22.2注解
是代码中的一种特殊标记,使用程序去读取代码中的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;//	@interface声明注解
//	注解中只有属性
@Retention(RetentionPolicy.RUNTIME)//运行期注解
@Target({ElementType.TYPE/*类注解*/,ElementType.FIELD/*属性注解*/,ElementType.METHOD/*方法注解*/,ElementType.PARAMETER/*参数注解*/})
public @interface MyAnnotation {//	属性String value();String name() default "tom";String[] arr();
}
 
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})
@interface Table {String name();
}@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@interface Field {String name();
}//	根据数据库中的Users表创建的 表中有name字段
@Table(name="emps")
class Users {@Field(name="name")private String name;
}public class Test02 {public static void main(String[] args) throws Exception {
//		加载类对象Class<?> forName = Class.forName("com.qf.test.Users");//		获取对应表的数据 获取的注解Table table = (Table) forName.getDeclaredAnnotation(Table.class);System.out.println(table);System.out.println(table.name());//		sql语句String sql = "select * from " + table.name();System.out.println(sql);}
}