package com.jqmobile.core.server.service;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.jqmobile.core.server.db.dao.DAOFactory;
import com.jqmobile.core.service.Service;
import com.jqmobile.core.utils.TypeArgFinder;
public class SimpleService<DAO>{
private Class<DAO> daoClass;
protected DAO getDao(){
return getDao(getDAOClass());
}
protected <T> T getDao(Class<T> c){
try {
return DAOFactory.instance(c);
} catch (Exception e) {
throw new RuntimeException("构建DAO失败", e);
}
}
@SuppressWarnings("unchecked")
private Class<DAO> getDAOClass(){
if(null == daoClass) daoClass = ((Class<DAO>) TypeArgFinder.find(getClass(), SimpleService.class, 0));
return daoClass;
}
@SuppressWarnings("unchecked")
protected <S> S getService(Class<S> c){
return (S) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{c}, new BaseInvocationHandler(c));
}
private final class BaseInvocationHandler implements InvocationHandler{
private Class<?> c;
BaseInvocationHandler(Class<?> c){
this.c=c;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Service annotation = c.getAnnotation(Service.class);
if(null == annotation){
throw new ServiceAnnotationException(c);
}
String impl = annotation.impl();
Class<?> ci = Class.forName(impl, false, Thread.currentThread().getContextClassLoader());
Object obj = ci.newInstance();
//
try{
Object result = method.invoke(obj, args);
return result;
}catch(Throwable e){
throw e;
}
//
}
}
}