import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyFactoryAnnotationCombine {
public static void main(String[] args) {
new MessageService().send();
}
}
@Retention(RetentionPolicy.RUNTIME)
@interface UseMessage{
Class<?> clazz();
}
@UseMessage(clazz = QQMessageImpl.class)
class MessageService{
private IMessage iMessage;
public MessageService(){
UseMessage useMessage = MessageService.class.getAnnotation(UseMessage.class);
try {
Class clazz = useMessage.clazz();
this.iMessage = (IMessage)MessageFactory.getInstance(clazz);
} catch (Exception e) {
e.printStackTrace();
}
}
public void send(){
this.iMessage.send();
}
}
class MessageFactory{
private MessageFactory(){}
public static <T>T getInstance(Class<T> clazz){
try {
return (T)new MessageProxy().bind(clazz.getDeclaredConstructor().newInstance());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
class MessageProxy implements InvocationHandler{
private Object object;
public Object bind(Object object){
this.object = object;
return Proxy.newProxyInstance(this.object.getClass().getClassLoader(), this.object.getClass().getInterfaces(), this);
}
public boolean connect(){
return true;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object retData = null;
try {
if(connect()){
System.out.println("链接成功");
retData = method.invoke(this.object, args);
}
return retData;
} catch (Exception e) {
throw new RuntimeException("连接失败");
}
}
}
class MessageImpl implements IMessage{
@Override
public void send() {
System.out.println("发送");
}
}
class QQMessageImpl implements IMessage{
@Override
public void send() {
System.out.println("qq发送");
}
}
interface IMessage{
void send();
}
|