public static CommonInterface getCommonInterface(Interface itf) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
Class c = Class.forName(itf.getClassName());
CommonInterface commonInterface = (CommonInterface) c.newInstance();
InterfaceInvocationHandler ih = new InterfaceInvocationHandler(commonInterface);
CommonInterface ci = (CommonInterface)Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), ih);
return ci;
}
根据类的全名,来获取响应的接口
其中itf.getClassName()=="com.xx.interface.impl.JlinterfaceImpl" ,JlinterfaceImpl该类是实现了CommonInterface 接口,
最后通过代理Proxy.newProxyInstance方法获取相应的接口
public class InterfaceInvocationHandler implements InvocationHandler{
private static final Logger log = LogManager.getLogger(InterfaceInvocationHandler.class);
private Object interfaceObj;
/**
* 构造函数
* @param interfaceObj
*/
public InterfaceInvocationHandler(Object interfaceObj) {
this.interfaceObj = interfaceObj;
}
/**
* 实现接口方法
* @param proxy
* @param method 被代理的类的方法名
* @param args 被代理的类方法里的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
//通过反射执行代理类的方法
result = method.invoke(this.interfaceObj, args);
} catch (Exception e) {
log.error("动态代理执行类方法出现异常!");
ExceptionPrintUtil.PrintErrorMessage(e, log);
}
return result;
}
}