import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Documented
@Target({METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DbInfo {//自定義標籤
String driver() default "com.mysql.jdbc.Driver";
String url() default "jdbc:mysql://localhost:3306/bbs";;
String usrename() default "root";
String password() default "root";
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//代理類
public class LiyuchunProxy{
//代理誰,通過構造方法賦值
private Liyuchun liyuchun = new Liyuchun();
//動態產生代理對象
public Star getProxy(){
return (Star) Proxy.newProxyInstance(
LiyuchunProxy.class.getClassLoader(),
liyuchun.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(
Object proxy,
Method method,
Object[] args) throws Throwable {
String money = (String) args[0];
if("sing".equals(method.getName())){
if("3".equals(money)){
//調用春哥的sing()方法
return method.invoke(liyuchun,args);
}else{
System.out.println("不夠出場費");
}
}else if("dance".equals(method.getName())){
if("5".equals(money)){
return method.invoke(liyuchun,args);
}else{
System.out.println("不夠出場費");
}
}else if("eat".equals(method.getName())){
System.out.println("春哥今天有事,不能來");
}
return null;
}
});
}
}
//參數一:loader表示動態代理對象是由哪個類加載器完成的
//參數二:interfaces表示動態代理對象與目標對象(春哥)有一樣的方法
//參數三:表示動態代理對象的欄截方法,即每次調用目標對象都會執行該invoke()方法(難點)
//invoke()方法的三個參數含義如下
//參數一:動態產生的代理對象本身
//參數二:method表示方法
//參數三:args表示方法參數