java通过服务名动态实例化
java通过服务名动态实例化对象并调用指定方法
第一步:定义服务的配置文件(指定服务名和服务路径)
?<? xml version = " 1.0 "? encoding = " gb2312 " ?>
?<!-- DOCTYPE service - config SYSTEM? " service.dtd " -->
?< service - config >
???? <!--? 用户服务? -->
???? < service name = " UserService "?? class = " com.xainfor.service.UserService "? template = " normal "?? />
???? < service name = " GnmkService "?? class = " com.xainfor.service.GnmkService "? template = " normal "?? />
?</ service - config >??
第二步:系统初始化是将所有服务名和路径加载到一个静态的HashMap中
? public?? class? ServiceConfig?? {
???
???? public?? static? HashMap serviceMap? =?? new? HashMap();
???
???? public?? static? String getService(String serviceName)?? {
??????? String serviceClass? =?? "" ;
??????? serviceClass? =? ServiceConfig.serviceMap.get(serviceName).toString();
???????? return? serviceClass;
??? }
}
第三步:定义一个接口类
? public?? interface? Service?? {
? public?? void? execute();
} 第四步:服务实例化类
public class ServiceExecuteHelper {
???
??? /** *//**
???? * 日志处理
???? */
??? private static final MsgLogger logger = MsgLogger.getLogger();
???
???? public static void execute(String servicename) {
???????? try {
??????????? //验证服务是否存在
??????????? String servicClass = ServiceConfig.getService(servicename);
??????????? //如果服务存在就加载服务信息
??????????? if (servicClass != null && !servicClass.equals("")) {
??????????????? Class classObject = Class.forName(servicClass);
??????????????? Service service = (Service) classObject.newInstance();
??????????????? service.execute();???????????????????????????
??????????? } else {
??????????????? logger.info("服务["+servicename+"]未定义");
??????????? }
??????? } catch(Exception e) {
??????????? logger.info("服务["+servicename+"]不存在!");
??????? }
???? }
}第五步:定义接具体服务并实现接口类
public class GnmkService implements Service {
??? /**//* (non-Javadoc)
???? * @see com.xainfor.service.Service#println()
???? */
??? public void execute() {
??????? // TODO Auto-generated method stub
??????? System.out.println("执行的是GnmkService");
??? }
}public class UserService implements Service {
???
??? public void execute() {
??????? // TODO Auto-generated method stub
??????? System.out.println("执行的是UserService");
???????
??? }
}第六步:测试类
public class testService {
??
??? public static void main(String [] temp) {
????? ServiceExecuteHelper.execute("UserService");
?? }
}