按照來源注解
java自帶的注解
@override
@SuppressWarnings
@Deprecated
第三方的注解
mybatis的注解
@Test
自定義注解
元注解
給注解標示注解
@Target(value={ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Hemi {
String value();
int num=100;
}
@Target指定注解可以放置的位置
ElementType.TYPE:放在類上
ElementType.METHOD:放在方法上
ElementType.FIELD:放在字段上
@Retention:指定注解在什么時候有用
RetentionPolicy.RUNTIME:運行時有用
RetentionPolicy.CLASS:編譯時有用
RetentionPolicy.RESOURCE:源文件有用
@Inherited:表示可繼承
得到注解的內容
Class<?> clazz=MyHemi.class;
Hemi annotation = clazz.getAnnotation(Hemi.class);
String value = annotation.value();
Method method = clazz.getMethod("insert");
Hemi annotation2 = method.getAnnotation(Hemi.class);
String value2 = annotation2.value();
System.out.println(value);
System.out.println(value2);
注解的作用
1.傳遞數據
2.標記
jdk動態代理
1.被代理類必須實現一個接口
public class Student implements Runnable{
@Override
public void run() {
System.out.println("跑步");
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.創建一個類實現InvocatiobHandler接口,該類用來對象代理對象進行方法的增強
public class TimeUntil implements InvocationHandler{
//將對象傳入進來
public Object target;
public TimeUntil(Object target){
this.target=target;
}
}
3.通過Proxy.newProxyInstance(ClasLoader, Class, InvovationHandler)來創建代理類對象并調用代理對象的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
long time1 = System.currentTimeMillis();
method.invoke(target, args);
long time2 = System.currentTimeMillis();
System.out.println(time2-time1);
return null;
}