注解与反射
一、java 1.5的新特新注解和枚举
二、本文主要讲解注解和反射的主题应用?
1、Java.lang包下游三个基本的注解分别是:Deprecated用 @Deprecated 注释的程序元素,不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。在使用不被赞成的程序元素或在不被赞成的代码中执行重写时,编译器会发出警告。
2、注释类型 OverrideOverride
表示一个方法声明打算重写超类中的另一个方法声明。如果方法利用此注释类型进行注解但没有重写超类方法,则编译器会生成一条错误消息。
3、注释类型 SuppressWarningsSuppressWarnings
指示应该在注释元素(以及包含在该注释元素中的所有程序元素)中取消显示指定的编译器警告。注意,在给定元素中取消显示的警告集是所有包含元素中取消显示的警告的超集。例如,如果注释一个类来取消显示某个警告,同时注释一个方法来取消显示另一个警告,那么将在此方法中同时取消显示这两个警告。如:
@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception{
System.runFinalizersOnExit(true);
}
三、定义自己的注解
下面是说明定义注解的方法,以及怎样查看API
下面是编写自己的注解的实例,此源代码有详细的解说,下面就只需大家运行一下代码即可:
这个是自己定义的注解类
package cn.itcast.day2;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import cn.itcast.day1.EnumTest;
/***
* 注解可以注入哪些属性呢?
* 可以注入注解的注解,数组,基本类型,String,枚举还以上类型的数组,还有Class
* 当注入数组只有一个值的时候可以写成如:
* @Target(ElementType.METHOD)
* @author Administrator
*@Retention注解的生命周期,注解类要经过三个生命周期,
*
SOURCE,注解就会在编译的时候注解类会抛弃
CLASS,注解类编译成class文件后不想保留在虚拟机里,则抛弃,这个是默认值
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
RUNTIME
*/
@Retention(RetentionPolicy.RUNTIME)//元注解,信息的信息就叫元信息
/**
* 这个注解的意思就是自定义的注解用户可以放在哪里进行注解
* 如:可以在属性、构造方法、方法、参数声明、类接口等
* 详细请查看文档ElementType枚举的类型
*/
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface ItcastAnnotation {
String color() default "blue";//default想让注解射入属性一个值
String value();
int[] arrayAttr() default {3,4,4};
EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");
Class getType();
}
这个是测试的代码
package cn.itcast.day2;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import cn.itcast.day1.ReflectPoint;
/***
* 如果@ItcastAnnotation注解类的属性有默认的值可以不注入值
* @author Administrator
*
*/
@ItcastAnnotation([email protected]("flx"),color="red",value="abc",arrayAttr=1,getType=ReflectPoint.class)
public class AnnotationTest {
@SuppressWarnings("deprecation")
//@ItcastAnnotation("xyz")
public static void main(String[] args) throws Exception{
System.runFinalizersOnExit(true);
if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
System.out.println(annotation.color());
System.out.println(annotation.value());
System.out.println(annotation.arrayAttr().length);
System.out.println(annotation.lamp().nextLamp().name());
System.out.println(annotation.annotationAttr().value());
//利用反射机制获取ReflectPoint类的实例
System.out.println(annotation.getType().getConstructor(new Class[]{int.class,int.class}).newInstance(2,3));
Method[] methods=annotation.getType().getMethods();
String methodName;
String fieldName;
Type type;
for(Method method:methods){
methodName=method.getName();
fieldName=methodName.substring(3).toLowerCase();
if(methodName.startsWith("set")){
System.out.println(methodName);
// type=method.getGenericParameterTypes()[0];//可以得到方法的参数类型
//System.out.println(type);
}
}
}
}
@Deprecated
public static void sayHello(){
System.out.println("hi,"得到");
}
这个是枚举类
package cn.itcast.day1;
import java.util.Date;
public class EnumTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WeekDay1 weekDay = WeekDay1.MON;
System.out.println(weekDay.nextDay());
WeekDay weekDay2 = WeekDay.FRI;
System.out.println(weekDay2);
System.out.println(weekDay2.name());
System.out.println(weekDay2.ordinal());
System.out.println(WeekDay.valueOf("SUN").toString());
System.out.println(WeekDay.values().length);
new Date(300){};
}
public enum WeekDay{
SUN(1),MON(),TUE,WED,THI,FRI,SAT;
private WeekDay(){System.out.println("first");}
private WeekDay(int day){System.out.println("second");}
}
public enum TrafficLamp{
RED(30){
public TrafficLamp nextLamp(){
return GREEN;
}
},
GREEN(45){
public TrafficLamp nextLamp(){
return YELLOW;
}
},
YELLOW(5){
public TrafficLamp nextLamp(){
return RED;
}
};
public abstract TrafficLamp nextLamp();
private int time;
private TrafficLamp(int time){this.time = time;}
}
}
这个是要注入的class类:ReflectPoint
package cn.itcast.day1;
import java.util.Date;
public class ReflectPoint {
private Date birthday = new Date();
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString(){
return str1 + ":" + str2 + ":" + str3;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}