欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java注解实际案例应用(结合工厂设计模式与动态代理和反射机制)

程序员文章站 2024-01-20 17:26:10
...

假设现在我们有这样一个场景,有一个电脑用户,需要通过代理类进行网络连接,发送QQ消息,请你提供将对应的真实实现类的信息保存在注解中,通过注解的方式获取service服务类。
代码如下

public class AnnotationFactoryTest {
    public static void main(String[] args) {
        IChannelService iChannelService = new IChannelService();
        iChannelService.send();
    }

}

@Retention(RetentionPolicy.RUNTIME)
@interface IChannelClass{
    Class<?> CLASS();
}

@IChannelClass(CLASS = ComputerUser.class)
class IChannelService{
    private IChannel iChannel=null;
    public IChannelService(){
        Class<?> aClass = IChannelService.class.getAnnotation(IChannelClass.class).CLASS();
        iChannel  = (IChannel) ProxyFactory.getProxyInstance(aClass);
    }
    public void send(){
        iChannel.send();
    }
}

class ProxyFactory{
    private ProxyFactory(){

    }
    public static <T> T getProxyInstance(Class<T> clazz) {
        try {
            return  (T) new IChannelProxy().bind(clazz.getDeclaredConstructor().newInstance());
        } catch ( Exception e) {
            e.printStackTrace();
            return  null;
        }
    }
}

interface IChannel{
    void send();
}

class ComputerUser implements IChannel{

    @Override
    public void send() {
        System.out.println("发送QQ消息~~~~");
    }
}

class IChannelProxy implements InvocationHandler{
    private Object target;
    public Object bind(Object target){
        this.target=target;
        return Proxy.newProxyInstance(this.target.getClass().getClassLoader(),this.target.getClass().getInterfaces(),this);
    }
    public boolean getConnect(){
        System.out.println("【代理类】获取网络连接....");
        return true;
    }
    public void close(){
        System.out.println("断开网络连接。");
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object returnData=null;
        if (getConnect()){
            returnData=method.invoke(this.target,args);
            close();
        }
        return returnData;
    }
}